The Activity Lifecycle, Revisited
Overriding onSaveInstanceState(Bundle) is not just for handling rotation. An activity can also be destroyed if the user navigates away for a while and Android needs to reclaim memory.
Android will never destroy a running activity to reclaim memory – the activity must be in the paused or stopped state to be destroyed. If an activity is paused or stopped, then its onSaveInstanceState(...) method has been called.
When onSaveInstanceState(...) 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.13).
Figure 3.13 The 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. However, you can always rely on onPause() and onSaveInstanceState(...) to be called. Typically, you override onSaveInstanceState(...) to stash small, transient states that belong to the current activity in your Bundle and onPause() for anything else that needs to be done.
Under some situations, Android will not only kill your activity but also completely shut down your application’s process. This will only happen if the user is not currently looking at your application, but it can (and does) happen. Even in this case, the activity record will live on and enable a quick restart of your activity if the user 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 typically discarded on reboot and may also be discarded if they are not used for a long time.