Search code examples
androidandroid-lifecycle

LifeCycles getting called when app is forcefully killed


Im using in my app the onDestroy method to clean up data.

Google's documentation says 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. 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.

So in this case, data and other user important information must be saved in onPause or orStop().

But according to this link, none of the lifecycles get called.

So where do we save our data?


Solution

  • But according to this link, none of the lifecycles get called.

    That answer is somewhat misleading. Your foreground activity should no longer be in the foreground when the user brings up the overview screen (recent tasks list). onPause() and onStop() will be called on that activity as a result. You can test this by overriding onPause() and onStop() and logging their calls.

    So where do we save our data?

    That depends a lot on what you are building.

    In some cases, save the data when the data changes and the user indicates that they want to hold onto this data.

    In some cases, save the data periodically. For example, in a game, you might save the game state every so often, so the user can pick up the game from where they left off.

    In some cases, using a lifecycle method (e.g., onStop()) as a data-save trigger can be OK, but other times not. Saying "we will save the stuff that the user has typed in when we get called with onStop()" might be fine. Saying "we will go ahead and charge the user's credit card when we get called with onStop()" might not be fine.