Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity's onDestroy() method not called after removing activity from background by swiping

Tags:

android

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?

like image 993
Pritish Avatar asked Jun 30 '16 08:06

Pritish


2 Answers

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.

like image 128
earthw0rmjim Avatar answered Oct 02 '22 20:10

earthw0rmjim


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)

like image 28
jpf Avatar answered Oct 02 '22 19:10

jpf