Android开发第2-4课:重建一个Activity

本课将会教你

There are a few scenarios in which your activity is destroyed due to normal app behavior, such aswhen the user presses theBack button or your activity signals its own destruction bycallingfinish(). The system may also destroy your activity if it'scurrently stopped and hasn't been used in a long time or the foreground activity requires moreresources so the system must shut down background processes to recover memory.

When your activity is destroyed because the user presses Back or the activity finishesitself, the system's concept of thatActivity instance is gone forever becausethe behavior indicates the activity is no longer needed. However, if the system destroysthe activity due to system constraints (rather than normal app behavior), then although the actualActivity instance is gone, the system remembers that it existed such that ifthe user navigates back to it, the system creates a new instance of the activity using a set ofsaved data that describes the state of the activity when it was destroyed. The saved data that thesystem uses to restore the previous state is called the "instance state" and is a collection ofkey-value pairs stored in aBundle object.

Caution: Your activity will be destroyed and recreated each timethe user rotates the screen. When the screen changes orientation, the system destroys and recreatesthe foreground activity because the screen configuration has changed and your activity might need toload alternative resources (such as the layout).

By default, the system uses the Bundle instance state to save informationabout eachView object in your activity layout (such as the text value enteredinto anEditText object). So, if your activity instance is destroyed andrecreated, the state of the layout is restored to its previous state with nocode required by you. However, youractivity might have more state information that you'd like to restore, such as member variables thattrack the user's progress in the activity.

Note: In order for the Android system to restore the state ofthe views in your activity,each view must have a unique ID, supplied by theandroid:id attribute.

To save additional data about the activity state, you must overridethe onSaveInstanceState() callback method.The system calls this method when the user is leaving your activityand passes it theBundle object that will be saved in theevent that your activity is destroyed unexpectedly. Ifthe system must recreate the activity instance later, it passes the sameBundle object to both theonRestoreInstanceState() andonCreate()methods.

Figure 2. As the system begins to stop your activity, itcallsonSaveInstanceState() (1) so you can specifyadditional state data you'd like to save in case theActivity instance must berecreated.If the activity is destroyed and the same instance must be recreated, the system passes the statedata defined at (1) to both theonCreate()method(2) and theonRestoreInstanceState() method(3).

保存你的Activity状态

As your activity begins to stop, the system calls onSaveInstanceState() so your activity can save state information with a collection of key-valuepairs. The default implementation of this method saves information about the state of the activity'sview hierarchy, such as the text in an EditText widget or the scroll positionof aListView.

To save additional state information for your activity, you mustimplement onSaveInstanceState() and addkey-value pairs to the Bundle object. For 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);
}

Caution: Always call the superclass implementation ofonSaveInstanceState() so the default implementationcan save the state of the view hierarchy.

恢复你的Activity状态


When your activity is recreated after it was previously destroyed, you can recover your savedstate from theBundlethat the systempasses your activity. Both theonCreate() andonRestoreInstanceState() callback methods receivethe sameBundle that contains the instance state information.

Because the onCreate() method is called whether thesystem is creating a new instance of your activity or recreating a previous one, you must checkwhether the stateBundle is null before you attempt to read it. If it is null,then the system is creating a new instance of the activity, instead of restoring a previous onethat was destroyed.

For example, here's how you can restore some state data in onCreate():

@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
    }
    ...
}

Instead of restoring the state during onCreate() youmay choose to implementonRestoreInstanceState(), which the system callsafter theonStart() method. The system calls onRestoreInstanceState() only if there is a savedstate to restore, so you do not need to check whether theBundle is null:

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);
}

Caution: Always call the superclass implementation ofonRestoreInstanceState() so the default implementationcan restore the state of the view hierarchy.

To learn more about recreating your activity due to arestart event at runtime (such as when the screen rotates), readHandling Runtime Changes.

posted @ 2017-07-13 16:34  IT媚娘  阅读(135)  评论(0)    收藏  举报