androidonrestoreinstancestate

How to tell the difference of the path of OnRestoreInstanceState?


I have somewhat problem with coping with OnSaveInstanceState/OnRestoreInstanceState pair. It is said it is for temporary saving of the state, the best example is when phone is rotated. This part works great for me.

However OnSaveInstanceState is called also when application simply quits. Several hours later I start app (from my perspective it is a new run), and to my surprise Android calls OnRestoreInstanceState and is able to dig out "old" values of the state.

This ruins my logic because my current code assumes this pair is called only when apps runs constantly (from user perspective), so in the second scenario half of my app behaves like it was just started (correct), while other half behaves like it is in the middle of processing some data (because it got such values from the preserved state; which is not intended).

Of course I could hack it and ditch this pair altogether and use global values in app instance, but I wonder how to do it correctly/gently without using big guns?

Update: important events that happen:

Gingerbread 2.3.

For the time being I ended up using global variables stored in application, because it is recreated on each launch, yet preserved on screen rotation it behaves as I would expect it.


Solution

  • Several hours later I start app (from my perspective it is a new run), and to my surprise Android calls OnRestoreInstanceState and is able to dig out "old" values of the state.

    On modern versions of Android, the saved instance state is only around for ~30 minutes, not several hours. However, that still may be after your process has been terminated while your app is in the background, to free up system RAM.

    I wonder how to do it correctly/gently without using big guns?

    Only use the saved instance state Bundle for the process-termination scenario.

    For configuration changes, if you were working on modern versions of Android, you would use a ViewModel. Your "Gingerbread 2.3" suggests that you are into retrocomputing, and few current libraries exist that will support such an old OS version. For a pure Android SDK solution for API Level 10, you would use onRetainNonConfigurationInstance() and getLastNonConfigurationInstance(). ViewModel is built (indirectly) on top of those methods.