When an activity is killed, it will fire one or both of the following two methods:
To preserve the state of an activity, you could always implement the onPause() method.
To preserve the state of an activity so that it can be restored later when the activity is recreated, a much simpler way is to implement the onSaveInstanceState() method, as it provides a Bundle object as an argument so that you can use it to save your activity's state.
The following code shows that you can save the string ID into the Bundle object during the onSaveInstanceState() method:
@Override public void onSaveInstanceState(Bundle outState) { //save whatever you need to persist outState.putString("ID", "1234567890"); super.onSaveInstanceState(outState); }
When an activity is recreated, the onCreate() method is first called, followed by the onRestoreInstanceState() method.
@ Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); //retrieve the information persisted earlier String ID = savedInstanceState.getString("ID"); }
Bundle object only support basic data types.
onRetainNonConfigurationInstance() method is fired when an activity is about to be destroyed due to a configuration change.
You can save your current data by returning it in this method, like this:
@Override public Object onRetainNonConfigurationInstance() { //save whatever you want here; it takes in an Object type return ("Some text to preserve"); }
This method returns an Object type, which allows you to return nearly any data type.
To extract the saved data, you can extract it in the onCreate() method, using the getLastNonConfigurationInstance() method:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.d("StateInfo", "onCreate"); String str = (String) getLastNonConfigurationInstance(); }