When exactly are onSaveInstanceState() and onRestoreInstanceState() called?

Viewed 72787

The following figure (from the official doc) describes the well-known lifecycle of an Android activity:

enter image description here

On the other hand, when the activity is destroyed by the system (for example because memory needs to be reclaimed), the state of the activity is sometimes automatically saved and restored by means of the methods onSaveInstanceState() and onRestoreInstanceState(), as illustrated by the following figure (also from the official doc):

enter image description here

I'm aware that onSaveInstanceState() is not always called when an activity is about to be destroyed. For example, if it is destroyed because the user has pressed the "back" button, the activity state is not preserved. But in the cases when the state is saved and restored, and onSaveInstanceState() / onRestoreInstanceState() get called, when exactly are they called?

For example, according to the above figures, onRestoreInstanceState() might be called before onStart(), or after onStart() but before onResume(), or after onResume(). Similarly, several possibilities exist for onSaveInstanceState(). So when are they called exactly?

Ideally, what I would like is to see a combined diagram showing the activity lifecycle states and the save/restore methods, if that exists.

5 Answers
String activityState;
@Override 
public void onCreate(Bundle savedInstanceState) {
// call the super class onCreate to complete the creation of activity like 
// the view hierarchy 
super.onCreate(savedInstanceState);

// recovering the instance state 
if (savedInstanceState != null) {
     activityState = savedInstanceState.getString(STATE_KEY);
 } 

   setContentView(R.layout.main_activity);
   mTextView = (TextView) findViewById(R.id.text_view);
} 

//This callback is called only when there is a saved instance previously saved using //onSaveInstanceState(). We restore some state in onCreate() while we can optionally restore // other state here, possibly usable after onStart() has completed. // The savedInstanceState Bundle is same as the one used in onCreate().

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) {
 mTextView.setText(savedInstanceState.getString(STATE_KEY));
  } 


// invoked when the activity may be temporarily destroyed, save the instance 
//state here 
//this method will be called before onstop

@Override 
 public void onSaveInstanceState(Bundle outState) {
    outState.putString(STATE_KEY, activityState);

    // call superclass to save any view hierarchy 
    super.onSaveInstanceState(outState);
} 
Related