As your activity begins to stop, the system calls onSaveInstanceState()
so your activity can save state information with a collection of key-value pairs. The default implementation of this method automatically saves information about the state of the activity's view hierarchy, such as the text in an EditText
widget or the scroll position of a ListView
.
To save additional state information for your activity, you must implement onSaveInstanceState()
and add key-value pairs to the Bundle object. For example:
public class MainActivity extends Activity {
static final String SOME_VALUE = "int_value";
static final String SOME_OTHER_VALUE = "string_value";
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
// Save custom values into the bundle
savedInstanceState.putInt(SOME_VALUE, someIntValue);
savedInstanceState.putString(SOME_OTHER_VALUE, someStringValue);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
}
The system will call that method before an Activity is destroyed. Then later the system will call onRestoreInstanceState
where we can restore state from the bundle:
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
someIntValue = savedInstanceState.getInt(SOME_VALUE);
someStringValue = savedInstanceState.getString(SOME_OTHER_VALUE);
}
Instance state can also be restored in the standard Activity#onCreate method but it is convenient to do it in onRestoreInstanceState
which ensures all of the initialization has been done and allows subclasses to decide whether to use the default implementation. Read this stackoverflow post for details.
Note that onSaveInstanceState
and onRestoreInstanceState
are not guaranteed to be called together. Android invokes onSaveInstanceState()
when there's a chance the activity might be destroyed. However, there are cases where onSaveInstanceState
is called but the activity is not destroyed and as a result onRestoreInstanceState
is not invoked.