Captain Obvious
Captain Obvious

Reputation: 785

Android contradicting documentation about lifecycle callbacks onPause() and onStop()

Intuitively, the most applicable callback to perform stuff in it would be onPause(). Yet, there seems to be a contradiction in the documentation:

According to https://developer.android.com/guide/components/activities/activity-lifecycle.html:

onPause() execution is very brief, and does not necessarily afford enough time to perform save operations. For this reason, you should not use onPause() to save application or user data, make network calls, or execute database transactions; such work may not complete before the method completes. Instead, you should perform heavy-load shutdown operations during onStop().

You should also use onStop() to perform relatively CPU-intensive shutdown operations. For example, if you can't find a more opportune time to save information to a database, you might do so during onStop().

According to https://developer.android.com/reference/android/app/Activity.html:

Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed. Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage.

So, where should it be done and on another spawned thread? How is this commonly done?

Upvotes: 2

Views: 109

Answers (1)

Onik
Onik

Reputation: 19949

Good catch!

Some notes to sum up:

  • don't use onPause() for "really heavy-load shutdown operations", otherwise you risk to get a negative user experience by slowing down a "next activity to be resumed until this method returns." In other cases go with it;
  • if you still hesitate, use onSaveInstanceState(). It's called between onPause() and onStop() and, AFAIK, is guaranteed to be called. The system relies on the method "so that when an activity has been killed, the system can restore its state coming back to it in the future";
  • regarding onStop(), personally I have never! experienced killing my app's process until the method returns, but seen SO questions stating so, which, as we know, corresponds to the official documentation. But, it's really very rare. So it's up to you whether to rely on it or not.

Upvotes: 1

Related Questions