Wednesday, February 23, 2011

Andoid Activity Life Cycle - onSaveInstanceState and onRestoreInstanceState

onSaveInstanceState and onRestoreInstanceState are two methods involved in Android Activity life cycle. There are several factors deciding when they will be called.

First, the data bundle mananged by these two methods are only valid within a single application running session. So if the application exits and restarts, then OnRestoreInstance will not be called, since no data are available. For the same reason, null is passed as parameter for onCreate method when onCreated is called in the first time.
MyActivity onCreate (null)
MyActivity onStart
MyActivity onResume

Second, onSaveInstanceState is always called before onPause method when starting to deactivate or close the Activity.
MyActivity onSaveInstanceState
MyActivity onPause

Third, in the same application session, onRestoreInstance will only be called if onDestroy has been called before it. Or in other word, onCreate is called before it.
MyActivity onSaveInstanceState
MyActivity onPause
MyActivity onStop
MyActivity onDestroy
MyActivity onCreate (obj)
MyActivity onStart
MyActivity onRestoreInstanceState
MyActivity onResume

A sample of full cycle looks as below:

MyActivity onCreate
MyActivity onStart
MyActivity onResume
MyActivity onSaveInstanceState
MyActivity onPause
MyActivity onStop
MyActivity onDestroy

MyActivity onCreate
MyActivity onStart
MyActivity onRestoreInstanceState
MyActivity onResume
MyActivity onSaveInstanceState
MyActivity onPause
MyActivity onStop
MyActivity onDestroy

Usually, onRestoreInstanceState will not be called since most of time the activity is still alive after it is stopped, as shown below:

MyActivity onCreate
MyActivity onStart
MyActivity onRestoreInstanceState
MyActivity onResume
MyActivity onSaveInstanceState
MyActivity onPause
MyActivity onStop
MyActivity onRestart
MyActivity onStart
MyActivity onResume


There are two ways to force the activity to be destroyed immediately.

The first way is changing the orientation of the simulator, it will force all activities to be destroyed and then created again. Another way is enabling Immediately destroy activities from dev tool's development settings page.

Jonathan

2 comments:

  1. Thanks :) That was very clear

    ReplyDelete
  2. Second, onSaveInstanceState is always called before onPause method when starting to deactivate or close the Activity.

    here what is exactly (deactivate or close the Activity)

    ReplyDelete