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

Per the documentation:

void onRestoreInstanceState (Bundle savedInstanceState)

This method is called between onStart() and onPostCreate(Bundle).

void onSaveInstanceState (Bundle outState)

If called, this method will occur after onStop() for applications targeting platforms starting with Build.VERSION_CODES.P. For applications targeting earlier platform versions this method will occur before onStop() and there are no guarantees about whether it will occur before or after onPause().


In addition to already posted answers, there is a subtle change introduced in Android P, which is:

void onSaveInstanceState(Bundle outState)

If called, this method will occur AFTER onStop() for applications targeting platforms starting with P. For applications targeting earlier platform versions this method will occur before onStop() and there are no guarantees about whether it will occur before or after onPause().

Source: docs

As to why this change is introduced, here's the answer:

... so an application may safely perform fragment transactions in onStop() and will be able to save persistent state later.

Source: docs


As per doc1 and doc2

onSaveInstanceState

Prior to Honeycomb, activities were not considered killable until after they had been paused, meaning that onSaveInstanceState() was called immediately before onPause(). Beginning with Honeycomb, however, Activities are considered to be killable only after they have been stopped, meaning that onSaveInstanceState() will now be called before onStop() instead of immediately before onPause().

onRestoreInstanceState

This method is called between onStart() and onPostCreate(Bundle) when the activity is being re-initialized from a previously saved state