@Override publicvoidonSaveInstanceState(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 protectedvoidonCreate(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 } // ... }
当然,恢复这个操作也可以在 onRestoreInstanceState 这个方法实现:
1 2 3 4 5 6 7 8
publicvoidonRestoreInstanceState(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); }