Home | History | Annotate | Download | only in activity-lifecycle
      1 page.title=Recreating an Activity
      2 parent.title=Managing the Activity Lifecycle
      3 parent.link=index.html
      4 
      5 trainingnavtop=true
      6 previous.title=Stopping and Restarting an Activity
      7 previous.link=stopping.html
      8 
      9 @jd:body
     10 
     11 <div id="tb-wrapper">
     12   <div id="tb">
     13     
     14     <h2>This lesson teaches you to</h2>
     15     <ol>
     16       <li><a href="#SaveState">Save Your Activity State</a></li>
     17       <li><a href="#RestoreState">Restore Your Activity State</a></li>
     18     </ol>
     19     
     20     <h2>You should also read</h2>
     21     <ul>
     22       <li><a href="{@docRoot}training/basics/supporting-devices/screens.html">Supporting
     23 Different Screens</a></li>
     24       <li><a
     25 href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a></li>
     26       <li><a href="{@docRoot}guide/components/activities.html">Activities</a>
     27       </li>
     28     </ul>
     29 
     30   </div>
     31 </div>
     32 
     33 <p>There are a few scenarios in which your activity is destroyed due to normal app behavior, such as
     34 when the user presses the <em>Back</em> button or your activity signals its own destruction by
     35 calling {@link android.app.Activity#finish()}. The system may also destroy your activity if it's
     36 currently stopped and hasn't been used in a long time or the foreground activity requires more
     37 resources so the system must shut down background processes to recover memory.</p>
     38 
     39 <p>When your activity is destroyed because the user presses <em>Back</em> or the activity finishes
     40 itself, the system's concept of that {@link android.app.Activity} instance is gone forever because
     41 the behavior indicates the activity is no longer needed. However, if the system destroys
     42 the activity due to system constraints (rather than normal app behavior), then althought the actual
     43 {@link android.app.Activity} instance is gone, the system remembers that it existed such that if
     44 the user navigates back to it, the system creates a new instance of the activity using a set of
     45 saved data that describes the state of the activity when it was destroyed. The saved data that the
     46 system uses to restore the previous state is called the "instance state" and is a collection of
     47 key-value pairs stored in a {@link android.os.Bundle} object.</p>
     48 
     49 <p class="caution"><strong>Caution:</strong> Your activity will be destroyed and recreated each time
     50 the user rotates the screen. When the screen changes orientation, the system destroys and recreates
     51 the foreground activity because the screen configuration has changed and your activity might need to
     52 load alternative resources (such as the layout).</p>
     53 
     54 <p>By default, the system uses the {@link android.os.Bundle} instance state to saves information
     55 about each {@link android.view.View} object in your activity layout (such as the text value entered
     56 into an {@link android.widget.EditText} object). So, if your activity instance is destroyed and
     57 recreated, the state of the layout is automatically restored to its previous state. However, your
     58 activity might have more state information that you'd like to restore, such as member variables that
     59 track the user's progress in the activity.</p>
     60 
     61 <p>In order for you to add additional data to the saved instance state for your activity, there's an
     62 additional callback method in the activity lifecycle that's not shown in the illustration from
     63 previous lessons. The method is {@link android.app.Activity#onSaveInstanceState
     64 onSaveInstanceState()} and the system calls it when the user is leaving your activity. When the
     65 system calls this method, it passes the {@link android.os.Bundle} object that will be saved in the
     66 event that your activity is destroyed unexpectedly so you can add additional information to it. Then
     67 if the system must recreate the activity instance after it was destroyed, it passes the same {@link
     68 android.os.Bundle} object to your activity's {@link android.app.Activity#onRestoreInstanceState
     69 onRestoreInstanceState()} method and also to your {@link android.app.Activity#onCreate onCreate()}
     70 method.</p>
     71 
     72 <img src="{@docRoot}images/training/basics/basic-lifecycle-savestate.png" />
     73 <p class="img-caption"><strong>Figure 2.</strong> As the system begins to stop your activity, it
     74 calls {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} (1) so you can specify
     75 additional state data you'd like to save in case the {@link android.app.Activity} instance must be
     76 recreated.
     77 If the activity is destroyed and the same instance must be recreated, the system passes the state
     78 data defined at (1) to both the {@link android.app.Activity#onCreate onCreate()} method
     79 (2) and the {@link android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} method
     80 (3).</p>
     81 
     82 
     83 
     84 <h2 id="SaveState">Save Your Activity State</h2>
     85 
     86 <p>As your activity begins to stop, the system calls {@link android.app.Activity#onSaveInstanceState
     87 onSaveInstanceState()} so your activity can save state information with a collection of key-value
     88 pairs. The default implementation of this method saves information about the state of the activity's
     89 view hierarchy, such as the text in an {@link android.widget.EditText} widget or the scroll position
     90 of a {@link android.widget.ListView}.</p>
     91 
     92 <p>To save additional state information for your activity, you must
     93 implement {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} and add
     94 key-value pairs to the {@link android.os.Bundle} object. For example:</p>
     95 
     96 <pre>
     97 static final String STATE_SCORE = "playerScore";
     98 static final String STATE_LEVEL = "playerLevel";
     99 ...
    100 
    101 &#64;Override
    102 public void onSaveInstanceState(Bundle savedInstanceState) {
    103     // Save the user's current game state
    104     savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    105     savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
    106     
    107     // Always call the superclass so it can save the view hierarchy state
    108     super.onSaveInstanceState(savedInstanceState);
    109 }
    110 </pre>
    111 
    112 <p class="caution"><strong>Caution:</strong> Always call the superclass implementation of {@link
    113 android.app.Activity#onSaveInstanceState onSaveInstanceState()} so the default implementation
    114 can save the state of the view hierarchy.</p>
    115 
    116 
    117 
    118 <h2 id="RestoreState">Restore Your Activity State</h2>
    119 
    120 <p>When your activity is recreated after it was previously destroyed, you can recover your saved
    121 state from the {@link android.os.Bundle} that the system
    122 passes your activity. Both the {@link android.app.Activity#onCreate onCreate()} and {@link
    123 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} callback methods receive
    124 the same {@link android.os.Bundle} that containes the instance state information.</p>
    125 
    126 <p>Because the {@link android.app.Activity#onCreate onCreate()} method is called whether the
    127 system is creating a new instance of your activity or recreating a previous one, you must check
    128 whether the state {@link android.os.Bundle} is null before you attempt to read it. If it is null,
    129 then the system is creating a new instance of the activity, instead of restoring a previous one
    130 that was destroyed.</p>
    131 
    132 <p>For example, here's how you can restore some state data in {@link android.app.Activity#onCreate
    133 onCreate()}:</p>
    134 
    135 <pre>
    136 &#64;Override
    137 protected void onCreate(Bundle savedInstanceState) {
    138     super.onCreate(savedInstanceState); // Always call the superclass first
    139    
    140     // Check whether we're recreating a previously destroyed instance
    141     if (savedInstanceState != null) {
    142         // Restore value of members from saved state
    143         mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    144         mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    145     } else {
    146         // Probably initialize members with default values for a new instance
    147     }
    148     ...
    149 }
    150 </pre>
    151 
    152 <p>Instead of restoring the state during {@link android.app.Activity#onCreate onCreate()} you
    153 may choose to implement {@link
    154 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}, which the system calls
    155 after the {@link android.app.Activity#onStart()} method. The system calls {@link
    156 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} only if there is a saved
    157 state to restore, so you do not need to check whether the {@link android.os.Bundle} is null:</p>
    158         
    159 <pre>
    160 public void onRestoreInstanceState(Bundle savedInstanceState) {
    161     // Always call the superclass so it can restore the view hierarchy
    162     super.onRestoreInstanceState(savedInstanceState);
    163    
    164     // Restore state members from saved instance
    165     mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    166     mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    167 }
    168 </pre>
    169 
    170 <p class="caution"><strong>Caution:</strong> Always call the superclass implementation of {@link
    171 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} so the default implementation
    172 can restore the state of the view hierarchy.</p>
    173 
    174 <p>To learn more about recreating your activity due to a
    175 restart event at runtime (such as when the screen rotates), read <a
    176 href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a>.</p>
    177 
    178