I'm new to android and I read a book for beginners which said that onSaveInstanceState(Bundle)
is ensured to be called before the system reclaims your Activity
.
I tried it on some test codes and found it incorrect. I found that onSaveInstanceState(Bundle)
was called every time after onPause()
was called. And it has nothing to do with system reclaimation.
I'm not very sure about it, so that's the question: when is onSaveInstanceState(Bundle)
called actually?
According to Android Documentation:
In addition, the method
onSaveInstanceState(Bundle)
is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received inonCreate(Bundle)
if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data inonPause()
instead ofonSaveInstanceState(Bundle)
because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
Yes onPause()
is called before onSaveInstanceState(Bundle)
. But onPause()
is guaranteed to be called as its a part of activity life cycle
Usually when your activity is re-created for example when you change device orientation then onSaveInstanceState(Bundle)
is called if you have not specified the android:configChanges
tag in your manifest.xml
file.