I have implemented ActivityLifecycleCallbacks
in a private class inside my Application
class.
If Home button or Back button is used, lifecycle's onStop()
and onPause()
methods are getting called. If I kill the activity by swiping out from background, onDestroy()
method is not getting called. It gets called when I start my activity next time. I am using moveTaskToBack(true)
in case of Back press.
What must be the issue and which lifecycle method should get called when we swipe out from background?
From the documentation of onDestroy()
:
Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.
Such a situation is swiping the app out of the recent tasks list.
Check out this answer on how to get notified when the app is getting swiped out of Recents.
I remember reading a similar question on StackOverflow. Here was the top answer:
Handle exit application from Task Manager Handle exit application from Task Manager
Unfortunately there isn't a good answer for handling this situation. If the app is force-killed, onDestroy method isn't necessarily called. According to the documentation.
Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here.
If you can, clean up in the onPause() method. In order for the user to get to that screen to kill the app, it has to have been backgrounded and thus onPause() would be called. (see documentation)
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