2

Concerning Android's Activity lifecycle, I've seen it widely claimed (on SO and elsewhere) that persistent data should be saved in the onPause() method, because there is no guarantee that onStop() will be called, since the OS may need to kill the activity to reclaim its resources if system resources are running low.

However, in a book I'm reading, the opposite is stated:

Practically speaking, the OS will not reclaim a visible (paused or resumed) > activity. Activities are not marked as "killable" until onStop() is called and finishes executing.

[Talks about stashed state and activity record a bit]

Note that your activity can pass into the stashed state without onDestroy() being called. You can rely on onStop() and onSaveInstanceState(Bundle) being called (unless something has gone horribly wrong on the device) ... Override onStop() to save any permanent data, such as things the user is editing, because your activity may be killed at any time after this method returns.

p70-71, Android Programming: The Big Nerd Ranch Guide, 3rd Edition (emphasis mine)


Multi-Part Question:

  • Is this (possibility of an app being killed before onStop() is called) something that is no longer true in and is still being propagated, or is the book outright wrong?

  • Is there some nuance to when or why an Activity might be killed that makes the answer "sometimes?"

  • If the book is correct, why is that misconception so widely spread? (E.g. Here, here, and here.)

References to official documentation would be appreciated.

Community
  • 1
  • 1
automaton
  • 495
  • 6
  • 16

1 Answers1

4

This is an illustration of Activity lifecycle : enter image description here

According to the official Android documentation,

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(). For more information about suitable operations to perform during onStop(), see onStop().

There is a case when the app go from onPause() to onCreate() without onStop() and onDestroy() is when another app with higher priority needs memory as you see the illustration.

Also, The activity could be destroyed without calling onStart(), onStop() when you call finish() method on onCreate() see reference

Imene Noomene
  • 3,035
  • 5
  • 18
  • 34