I have an app that has a list of menu items. When you click a menu item it opens a corresponding activity. Now in that new activity when you click the back button and return to the main list, that activity gets killed and it does not return to its past state when you start it again.
My question is, is it possible to not kill the activity when you leave it?
I tried saving values like so:
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("TO_REMEMBER", "Remember this");
}
However once the activity gets killed and than re-started, the oncreate method is not reading any data:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
//This is not getting fired
Toast.makeText(this, savedInstanceState.getString("TO_REMEMBER"), Toast.LENGTH_LONG).show();
}
}
Any help on this is appreciated.
Your are saving state using onSaveInstanceState
but that is not meant to save state across activity life-cycle when you press back. That is meant to save state across orientation changes etc. That needs to be done if you want to save some state across orientation change, so you are right there.
Now to save something across activity life-cycles, you have two options:
getPreferences
and store it using this. This will store it for that specific Activity only. I ll recommend this if you are trying to store the state of activity. Edit:
Well leaving Activity alive is not a recommended/documented approach. You can have Service
running in the background but does not contain UI as Activity
does. If you press Home button instead of Back then it will act something like orientation change.
In short, Activity is responsible for saving its state. That said, some UI controls save their state themselves so you dont have to save their state example EditText will save its state.
Ref:
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.