The Activity Lifecycle, Revisited

Overriding onSaveInstanceState(Bundle) is not just for handling rotation or other runtime configuration changes. An activity can also be destroyed by the OS if the user navigates away for a while and Android needs to reclaim memory (e.g., if the user presses Home and then goes and watches a video or plays a game).

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.

Stopped activities are fair game to be killed, though. Still, not to worry. If an activity is stopped, that means onSaveInstanceState(Bundle) was called. So resolving the data-loss-across-rotation bug also addresses the situation where the OS destroys your nonvisible activity to free up memory.

How does the data you stash in onSaveInstanceState(Bundle) survive the activity’s death? When onSaveInstanceState(Bundle) is called, the data is saved to the Bundle object. That Bundle object is then stuffed into your activity’s activity record by the OS.

To understand the activity record, let’s add a stashed state to the activity lifecycle (Figure 3.14).

Figure 3.14  The complete activity lifecycle

Figure shows complete activity lifecycle.

When your activity is stashed, an Activity object does not exist, but the activity record object lives on in the OS. The OS can reanimate the activity using the activity record when it needs to.

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). Typically, you override onSaveInstanceState(Bundle) to stash small, transient-state data that belongs to the current activity in your Bundle. 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.

So when does the activity record get snuffed? When the user presses the Back button, your activity really gets destroyed, once and for all. At that point, your activity record is discarded. Activity records are also discarded on reboot.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.15