How to save Activity state in Android ?
In an application, it is essential to be able to save user context between pauses. By pause, I mean when a user change his current application for example when he receives a call. After this pause, he will want to return to the previous application and it will be logical for him that the application be in the same state before his pause.
To achieve that in Android, you must be aware about Activity lifecycle. Activity lifecycle is defined by Android OS and it lets you to interact at some specific point. Theses points are some methods called in an Activity.
1. Activity lifecycle
First step to manage Activity lifecycle is to know what is the Android lifecycle. Following diagram sums this lifecycle :
This diagram presents different states in which an application can be and also methods called in Activity instance by OS when it passes from one state to another.
2. Save / Restore Activity state
Besides these callbacks methods, Activity class has 2 others methods you must override when you want to save activity state. Values saved are stored in a Bundle object that is essentially a Name-Value Pair map.
These 2 methods are :
- onSaveInstanceState
- onRestoreInstanceState
Method onSaveInstanceState is the moment you can save values you want be restored when activity will be recreated after a pause.
Method onRestoreInstanceState is the moment you can get stored values and restore saved state for current Activity.
Following code lets you accomplish the job :
@Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putBoolean("myBoolean", true); savedInstanceState.putDouble("myDouble", 1.9); savedInstanceState.putInt("myInt", 1); savedInstanceState.putString("myString", "Welcome from SSaurel"); // you can also save serializable objects } // ... @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); boolean myBoolean = savedInstanceState.getBoolean("myBoolean"); double myDouble = savedInstanceState.getDouble("myDouble"); int myInt = savedInstanceState.getInt("myInt"); String myString = savedInstanceState.getString("myString"); }
To return to the previous diagram, you must note that saved Bundle is also passed in parameter of the onCreate method of Activity. So, you can also restore saved values a this point if you want.
2 Comments Already
Leave a Reply
You must be logged in to post a comment.
You can also checkout the Droidcon presentation of the amazing Cyril Mottier about Android state restoration.
Here is the link: http://cyrilmottier.com/2014/09/25/deep-dive-into-android-state-restoration/
Definitely a great link.