Android has a facility for persisting Activity (or Fragment) state.
If your Activity is put into background it might be destroyed at some point and you don't have control over it. This is why Android uses Bundles. Store your data inside the bundle then read it back in
onCreate(Bundle savedInstanceState)
so before your activity dies for any reason, store important values:
protected void onSaveInstanceState(Bundle bundle) {
bundle.putInt(SOME_IMPORTANT_INT,mMyInt);
bundle.putString(SOME_IMPORTANT_STRING,mMyString);
}
when activity is created we have to read what is in the bundle (if there is anything at all):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null) {
mMyInt = savedInstanceState.getInt(SOME_IMPORTANT_INT);
mMyString = savedInstanceState.getString(SOME_IMPORTANT_STRING);
}
}
In short, what ever happens to your activity mMyInt and mMyString values are restored.
We might have a little control over when activity are restarted. This is done by android:configChanges attribute in the AndroidManifest file:
<activity
android:name=".ui.login.LoginActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
http://developer.android.com/guide/topics/resources/runtime-changes.html