As we already know if we want to save state of an activity we usually go for onSaveInstanceState(Bundle outState)
, but this method works only for primitives and parcelable.
I thought onRetainCustomNonConfigurationInstance
was a helper that can save arbitrary objects such as a bound service connection. It was working flawlessly during configuration changes(such as screen rotation) and I could restore the objects I saved. However, after I turn on the "do not keep activities" setting on emulator (according to doc: When this option is enabled, the Android OS will destroy an activity as soon as it is stopped. It is intended to help developers debug their apps. For example, it can simulate the case that Android will kill an activity in the background due to memory pressure. ), onRetainCustomNonConfigurationInstance
is never getting called when I navigate to another activity(at the same moment the first activity is destroyed by the OS). Thus I couldn't restore my previous objects by calling getLastCustomNonConfigurationInstance
. At the same time however, onSaveInstanceState(Bundle outState)
works just fine.
Now I have three questions:
What's the difference on activity saving and restoring between a configuration change (screen rotation) and a tight memory caused activity shut down (and when we navigate back it gets restored)? To me in these two cases the activity are both shut down by the OS, then why are they performing differently?
Is
onRetainCustomNonConfigurationInstance
only designed for saving instance during configuration change, but nothing else?Is the "don't keep activities" setting really simulating just like the OS kills activities? or it does something special that causes the difference?