Testing onSaveInstanceState()

Under severe resource shortage scenario, Android can terminate a background activity and even its process. Android makes sure that onSaveInstanceState(Bundle bundle) is called before the activity is killed. The activity can save any uncommitted application state data in the bundle. If user attempts to navigate back to the killed activity, Android will create a new instance and call onCreate(Bundle bundle). The supplied bundle will contain any previously saved state. Alternatively, Android also calls onRestoreInstanceState(Bundle bundle). The activity should attempt to recreate the state from the bundle. If all goes well, user will have no idea that the activity was killed.

Fortunately, most UIView widgets automatically save and restore their states. You need to deal with any other custom state information, for example, current position of a photo in a slide show application.

Keep in mind that invocation of onSaveInstanceState() does not mean that the activity is about to be killed. Android can decide to call it any time after an activity has been paused. Only if the activity was truly killed that onCreate() will receive a non-null bundle and onRestoreInstanceState(Bundle bundle) is called.

Testing state restoration from onCreate() or onRestoreInstanceState() can be tricky. How do you make sure that your activity is killed while in the background? Fortunately, the Dev Tools application that comes with every emulator image comes handy.


Launch Dev Tools. The click Development Settings.


Check Immediately destroy activities.

Now, as soon as an activity goes into background (stopped state), Android will kill it. When you bring the activity to foreground, a new instance will be created and onCreate() will receive a non-null bundle.

The Dev Tools application has special permissions not available to third party applications. This makes it difficult to install in an actual device. Technically it can done by installing a custom ROM but will be a lot of work.

One thought on “Testing onSaveInstanceState()

  1. hello, very nice explanation.

    I am new to android. working on tab vesrions. here im applying different layouts for landscape an portrait mode . how to selected option in portrait mode to landscape mode. suppose activity is have 3 fragments replacing one by one, when i rotate to landscape complete actiivty is loosing state, first fragment is displaying. how can i solve the problems.can u help me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s