Run code when Android app starts and exists - android

In my app I need to call code whenever the app closes (pauses) and then run code again whenever the app starts again (resumes). For example, I call a web service that syncs the data whenever the app starts or exits. This is easy in iOS because of the central app resume and suspend methods.
I understand the OnPause and OnResume in the Activity, however, is there a central way to handle this? The user could leave the app on Activity3 and come back later, or be in another screen, etc. I'd hate to have to have the same code in every Activity's OnPause and OnResume to handle the "app" startup and shutdown code routines.
Any suggestions?
Thank you.

You could make a common Activity which just handles onResume() and onPause() in a certain way and then make every Activity extend from that one instead of Activity directly.

I would consider subclassing Activty, have each of your activities extend that and just do what you need to when any of them pause or resume.
You could use some static members in an Application class that your new activity base uses to track state or store whatever you need.
Also, Application class has an onCreate() method which will run each time the application is started. There is no pause or resume for Application, however.

Creating a main Activity that is extended by all your other activities and override the onPause and onResume.
But the problem you will face if you want to extend another Activity class such as a ListActivity.
Another approach is to create a new class that extends application and override its onCreate and create a static method that acts as onPause and manually call it by each of your activities

Related

How to know if Application class was called before Activity launch?

We have Splash extends Activity which is the starting activity of our application. We also have CustomApplication extends Application class which is invoked when the app process in invoked.
Now we have the following requirement. Whenever the app/process is launched, call Utils.doSomeDBWork() function.
For this purpose we have put this function call in onCreate() of Splash and CustomApplication classes. The reason that we have put this call inside CustomApplication is that our application can be launched via deeplinks/notifications in which Splash won't be called. But the problem is that if the app was killed and launched via Splash, then the same function will be called twice. One from CustomApplication and the other through Splash.
So basically my question is that if the function has already been called from CustomApplication, then don't call this function from Splash. I can think of doing it by using some static variable or Shared Preferences. But don't think that this is a clean way. Is there any other way to achieve this, like passing some info through Intents etc?
How to know that Application class was called before Activity launch?
In brief, every time when Android "gets a request" to start any of your app component (Activity, Service, BroadcastReceiver) and your app isn't running yet, it forks the app_process (a.k.a zygote), changes its name to your.package.name defined in AndroidManifest.xml, initializes an Application instance, calls its onCreate() method, then instantiates the component requested and calls its lifecycle methods (Activity's onCreate(), Service's onCreate() or BroadcastReceiver's onReceive()).
For this purpose we have put this function call in onCreate() of splash and CustomApplication classes.
It's redundant. It's enough to call it only from Application's onCreate() which is the earliest "entry point" to an app that is guaranteed to be called before any other component's lifecycle methods. There can be only single instance of Application class which lives untill the app process dies.
You can easily test it by logging each of the lifecycle methods. After that you won't have any doubts left.
EDIT w.r.t the OP's comment:
If the app process was running and the user back presses and exits, and then launches the app again, then CustomApplication class won't be called.
This is only partially true. CustomApplication's onCreate() won't be called unless the system kills the app process while it is in background (simulate the case by, for example, swiping your app from Recents).
But our requirement is that CustomApplication class should be invoked in this case.
It's out of developer's scope. Only the system controls that.
That being said, CustomApplication's onCreate() will be called if Android kills the app in background. If it doesn't, a simple way to achieve the requirement is to have a boolean flag in CustomApplication which would indicate if Utils.doSomeDBWork() was called.
Why don't you call from only applcation's class onCreate?
when App is launched from deeplinks/notifications or Splash, Applcation will always be created first.
Also you can check from static variable.
like below.
class Utils{
public static boolean doneWork = false; // this static variable will be false when app process is killed.
public doSomeDBWork(){
if(!doneWork){
//alreay done..
return;
}
:
:
doneWork = true;
}
}
You could do some controls with ActivityLifeCycleCallbacks on application layer. If using it in splashActivity is a solution for you,track your activities and make call in your callback. I hope it gives an idea.

best place to add an action when application starts up or returns to the forground

I need my application to do 2 network calls when ever the app is started for the 1st time, when it has been killed and started again as well as when it has been placed in the background then returned.
I know I can put it in my "MainActivity" onCreate/onResume. I have a class that extends Application which is where I am initialising logging and crash reporting, but I noticed there is no onResume method, which from my understand is the method that is called when the application comes from the background.
Where would be the best place to do these 2 network calls to update certain aspects in my app when the app is started for the 1st time, started when killed and resumed when it comes back from the background.
FYI. The reason I don't want it to go in my "MainActivity" is that I don't want these network calls to be called when ever i return to the MainActivity from another screen in the app, only when the user returns to the app?
Thanks
The use case of calling whenever the app returns from background is by implementing Activity Life Cycle methods in your Application class:
public class myApp extends Application implements Application.ActivityLifecycleCallbacks {
...
}
In this case you make sure that whenever an onPause() is called a corresponding onResume() should also be called (i.e. normal screen switching). If not, then you know that your app is now in background. The next callback to onResume() should mean that it has come to foreground again and you can make your network call.

Android onResume and onCreate

I have a question regarding the logic of the life cycle of activities:
When I learned Android, setting up an Activity was always done in the onCreate() function. Now when I resume my Activity, there might be stuff to be done in the onResume() that has already been done in onCreate(). But then, why would we not just put all the stuff into onResume()?
why would we not just put all the stuff into onResume()?
Well onCreate() is called when your Activity is created and you need to initialize some very important things of your application like your main layout!.
Because some staff you don't want to do all the time activity resumed (like findViewById), It can be done once.
Activity can be resumed many times (with dialogs, for example). Do not waste resources.
OnCreate Method start when you open the activty for first time or open activity after kill app so you should locate all stuffs you need to initialize for once like setContentView or some variables.
For example when you run your app with IDE , on create method will call
But if after creating activity press home button activity will pause
And then open the app with recent app to call onresume() method
For better realize initialize all activity method with Log.i(tag,text)

Application context gets killed but activity not

I'm working on an application which has a few Activities. One Activity starts the next one. To share some Values I'm using a custom implementation of Application (I'm talking about android.app.Application) called MyApplication.
As we all know, the Android system kills an app, if it needs more space. But this leads to a problem:
I open my app and use it just like any other app
I close it (Home Button) and use other apps
The system will kill my application because it's wasting memory
When I reopen my App, it wants to open the last activity I used and I get a force close, because the values in MyApplication are null
The strange thing is, that the system destroys my Application, but it seems like it keeps the Activity. I don't really understand why this is so because the Application doesn't seem to have a life cycle.
What I want to have:
When MyApplication (whole Application, not only the activity) gets killed, I want the last activities to be killed too. So when I reopen the App, it starts the main acitvity provided by the manifest.xml.
or
The values in MyApplication are persisted and don't get lost if the Application gets destroyed. (I'm talking about a few objects so i think the shared preferences won't work).
I don't want to use a service to bind my activities to, but is there a similar way to tell the system that my last used activity depends on the application-context?
I hope you understand what my problem is and someone can help me out with this.
The right way to do things would be to save your application state.
Override the onSaveInstanceState(Bundle savedInstanceState) method to save your state and onRestoreInstanceState to retrieve it.
If you need to save large sets of data consider using a SQL database
You should make sure the app closes and restarts the way you want it to in the onPause() , onResume() and onStop() methods. Check out savedInstanceState which can save the state of the app (and restore it, when it's sent as a parameter to onCreate)
In your custom implementation of Application, add a Flag say :
public boolean appContextExist = false;
On your first Activity set the flag to true,
Override onCreate and onResume method on your Activity which need the contexts, add following :
MyApplication myApp = ((MyApplication) getApplicationContext());
if (!myApp.appContextExist) {
// Code to return to start activity here
}

Android OnApplicationPause/OnApplicationResume

Is there any way to handle when my android application goes into background and back?
I want to use notification service for a on-line game - I use a service, which shows an alert when something happens in the game. I want alerts to show only if my application is active (on the foreground), so I need to start my service when application goes foreground and stop it when application goes background.
Note that I cannot use Activity.OnPause/OnResume methods. I have many activities in my application, and if I'll handle OnPause/OnResume, it is possible in a moment, when a user swtches one activity to another, application will look like background, thorough it will be foreground actually
Note that I cannot use Activity.OnPause/OnResume methods. I have many
activities in my application, and if I'll handle OnPause/OnResume, it
is possible in a moment, when a user swtches one activity to another,
application will look like background, thorough it will be foreground
actually
Why don't you write a base class that extends Activity and enables or disables the service in these methods? After that extend all your activities from this base activity.
All you have to do is call the superclass method if you override these methods in your activties, e.g. by calling super.onResume() inside onResume(), to make sure these get still called. If you don't override them, everything works directly.
Not a clean way of doing this that I know of but,
You could perhaps send an Intent to your Service onCreate() and onPause() with a unique identifier.
You Service can then start a timer (with a delay which will be longer than the difference between onPause and onCreate being called in each activity) which, if not notified of an onCreate() within this time will set the Activity as "Paused".
If you add this functionality in a parent class which extends Activity you can then pull this same functionality into every class by extending that it rather than Activity (with the contract that you must call super.onCreate() and super.onPause() in each respective method).
Problem solved in a following way (C# code, mono for android)
class MyService : Service{
OnSomethingHappened(){
ActivityManager am = (ActivityManager) GetSystemService(ActivityService);
if(am.RunningAppProcesses.Any((arg) =>
arg.ProcessName == "myprocessname" &&
arg.Importance == ActivityManager.RunningAppProcessInfo.ImportanceForeground
)){
Trace("FOREGROUND!!!!");
}else{
Trace("BACKGROUND!!!!");
}
}
}

Categories

Resources