Android: onDestroy() or similar method in Application class
There is no such call back on a production device for the Application class.
The things you want to do should usually be done right after the changes are made, or in the onPause()
of the respective app component.
In android, there is no concept of closing an app. The user just leaves: this is the only event that you will be aware of (onPause()
in an activity). You should design your app so that it fits this lifecycle.
Typically, you should save any changes immediately but asynchronously, so that the UI doesn't hang. This is much better than saving changes in onPause()
because if something bad happens before the app is paused (the app crashes, the user runs out of battery), all data was already saved properly.
SharedPreferences
already save changes asynchronously so if you use that, you have nothing else to do. Otherwise you can use Kotlin coroutines or if you use Java, the good old AsyncTask
is great.
First of all: I'm an absolute beginner
I need to execute some code when my app exits (yes, I know not such thing in Android) and this works ok for me:
-I have MyApplication wich extends Application. As a member of MyApplication there is an AtomicInteger field named activeActivitiesNumber and a public getter method.
-All the application activities extend MyActivy (which itself extendes Activity)
-MyActivity overrides onCreate, onResume and onStop methods and also have a protected field: Protected MyAppication mAppState;
a) OnCreate(){
super.onCreate();
mAppState=this.getApplication();...}
b) onResume(){
super.OnResume();
myAppState.getactiveActivitiesNumber().addAndGet(1)
....}
c) onStop(){
super.onStop()
if (myAppStatemyAppState.getactiveActivitiesNumber()..decrementAndGet()<1){
...call exiting code (for instance a public method defined in MyApplication}
}
It has a problem: if you start any activity tan doesn´t belong to your application (for instance send an email) it will fire the exiting method.
Another problem (don´t know if it is a real o theoretical one) is that there is no guarantee tan in some situations onStop will be called.
Hope this help.
You can override onDestroy()
in the Activity
which will be the last one closed in your app and check if it's finishing. In this case your code will not be invoked on a device rotation. But you should be aware that onDestroy()
is not invoked when an app is closed through device home button.
@Override
public void onDestroy(){
super.onDestroy();
if(isFinishing()){
//do your stuff here
}
}