Search code examples
androidandroid-lifecycleonsaveinstancestate

Can onSaveInstanceState() be called manually?


I'm trying to save and retrieve my Activity's onSaveInstanceState() when clicking the back button. I have read that by default it is not saved because it is assumed that the user is done with the Activity when clicking back. However, in my app, this is not the case and I would like to call onSaveInstanceState() from within:

@Override
public void onBackPressed() {
    super.onBackPressed();
}

It is, however, saved on screen rotation. This I have read is also default behaviour.

I have spent a couple of days trying to hack this, but I'm just not getting anywhere.


Solution

  • I'm trying to save and retrieve my activities savedInstanceState when clicking the back button. I have read that by default it is not saved because it is assumed that the user is done with the activity when clicking back.

    All is correct. Moreover, in this case Android assumes the app is no longer needed for user so it can safely terminate the app process.

    Can saveInstanceSate be called manually?

    Of course. The method is protected. But it doesn't make sense as per your requirement. In your case, even though the "manual" Bundle you pass as a method parameter will be saved by the system, the data residing in RAM will be immediately vanished with the app process itself due to the back press.

    It is, however, saved on screen rotation.

    Also is correct. In this case Android assumes the app is still in use, so it cares (partially) for restoring its state for you.

    However, in my app, this is not the case and I would like to saveInstanceState from within onBackPressed().

    I doubt you should struggle the OS idiom. Android provides you alternative options to restore the app state (so a user "thought" he/she got back to your app exactly at the point it was left), e.g. SharedPreferences, database, internal storage etc. I recommend to stick the OS idioms.