Save Persistent Data In OnPause() Or OnStop()?
Solution 1:
You should save any critical data in onPause
because it is always called when your activity loses focus or user is exiting the app. On the other hand, onStop
is only called when the user is exiting the app, but not when they switch to a different activity(loses focus). Also, when your activity is in the background, android will forcefully kill your app process on low memory in which case onStop
will not be called, onDestroy
is called. So, onPause
is where you should run your persistence code, no need to do it in onStop
Solution 2:
Is is true that when your application needs to save some persistent data you should always do it in onPause() method in addition to the onStop() method
SHORT ANSWER : TRUE , onPause()
is even more reliable than onStop()
. And the chances of killing the process without invoking onStop()
and onDestroy()
are the highest.
WHY ?
The Activity life cycle diagram is the best aid in this scenario:
You can clearly see the order in which the methods are invoked. The safest choice as you can see is the onPause()
, which provides the first indication that the user is leaving your Activity, and then comes the onStop()
which indicates the app has entered to the Stopped state . And finally comes the onDestroy()
method. So it's safest to choose onPause()
to save the persistent data at the earliest.
FURTHERMORE : The chance and correlation between Activity states and ejection is clearly provided in this table : Activity state and ejection from memory
Post a Comment for "Save Persistent Data In OnPause() Or OnStop()?"