What happens is this, when the application loses focus, it starts a cycle that is part of the Lifecycle of an Android application, when an Activity is no longer visible (nor in the foreground) the method onStop
is called this means that from this moment, the system (whose management has some version changes to Android version) may decide to destroy this Activity (calling the method onDestroy()
).
Android Life Cicle:
When the system destroys your Activity, it stores the state of the Activity in the Bundles, for that all Views need to have Ids to be identified.
However, not always Android hits, and restores everything as you want, so if it is important that Activity keeps certain behavior, the ideal is that you do not depend on Android to do this and ensure that in any version, your view will maintain the behavior.
So you need to overwrite the method onSaveInstanceState
and onRestoreInstanceState
, and process the data saved in onCreate
Example:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
Source Android Docs.
Opa, but in the case of some open dialog, how can I do it?
– Rubens Ventura
Dude, I may be wrong, but Dialog extends an object, so I think you can store the entire object in the Bundle and display it again. Another solution is to use a Dialogfragment, so you can take care of its cycle part, as in this link: http://stackoverflow.com/questions/7557265/prevent-dialog-dismissal-on-screen-rotation-in-android/15729764#15729764
– Lucas Queiroz Ribeiro