I am extending Application class to work with some global variables that need context. I know there is onCreate() method in the Application class that gets called before any other onCreate() in activities, but I would like to know if there is onDestroy() or similar method in the Application class that could be overridden so that I would be able to store variables in persistent memory, unregister listener and send last message to server before app process gets killed? If not, is there any other way to do that?
Answer: onPause() and onStop() will not be invoked if finish() is called from within the onCreate() method. This might occur, for example, if you detect an error during onCreate() and call finish() as a result. In such a case, though, any cleanup you expected to be done in onPause() and onStop() will not be executed.
onDestroy( ) is called before the activity is destroyed. The system invokes this callback either because: the activity is finishing (due to the user completely dismissing the activity or due to finish( ) being called on the activity), or.
onDestroy: The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space.
Once onStop() is called then onRestart() can be called. onDestroy() is last in the order after onStop(). onDestory() is called just before an activity is destroyed and after that it is gone it is not possible to resurrect this.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With