简体   繁体   中英

onRestoreInstanceState is not being called on Back button pressed

I'm trying to save and restore application state as savedInstanceState.

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt(STATE_Tracker, 1);
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

   int value = savedInstanceState.getInt(STATE_Tracker);

    if (value==1){

    }
    else {

    }
}

That code works when home button pressed. But if I press back button, and run the app again, its not working.

Any help?

From developers guide:

When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed. However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a Bundle object.

In other words, when you press the back button, you will not have restore behavior the lifecycle of the activity is considered completed and no longer needed, thus you don't need to restore the instance state. If you do need however you could override

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

And persist the state in any storage option like SharedPreference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM