Note that onStop()
and onDestroy()
are usually killable. After that method returns the process hosting the activity may killed by the system at any time without another line of its code being executed. Because of this, you should use the onPause()
method to write any persistent data (such as user edits) to storage.
In addition, the method onSaveInstanceState(Bundle)
is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle)
if the activity needs to be re-created.
For example, consider the following application code snippet:
public class DemoActivity extends Activity {
...
static final int DATA_ONE = 0;
static final int DATA_TWO = 1;
private SharedPreferences mPrefs;
private int mData;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences mPrefs = getSharedPreferences();
mData = mPrefs.getInt("data_no",DATA_ONE);
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor ed = mPrefs.edit();
ed.putInt("data_no", mData);
ed.commit();
}
}