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 although 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 save 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 restored to its previous state with no
     58 code required by you. However, your
     59 activity might have more state information that you'd like to restore, such as member variables that
     60 track the user's progress in the activity.</p>
     61 
     62 <p class="note"><strong>Note:</strong> In order for the Android system to restore the state of
     63 the views in your activity, <strong>each view must have a unique ID</strong>, supplied by the
     64 <a href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code
     65 android:id}</a> attribute.</p>
     66 
     67 <p>To save additional data about the activity state, you must override
     68 the {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} callback method.
     69 The system calls this method when the user is leaving your activity
     70 and passes it the {@link android.os.Bundle} object that will be saved in the
     71 event that your activity is destroyed unexpectedly. If
     72 the system must recreate the activity instance later, it passes the same {@link
     73 android.os.Bundle} object to both the {@link android.app.Activity#onRestoreInstanceState
     74 onRestoreInstanceState()} and {@link android.app.Activity#onCreate onCreate()}
     75 methods.</p>
     76 
     77 <img src="{@docRoot}images/training/basics/basic-lifecycle-savestate.png" />
     78 <p class="img-caption"><strong>Figure 2.</strong> As the system begins to stop your activity, it
     79 calls {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} (1) so you can specify
     80 additional state data you'd like to save in case the {@link android.app.Activity} instance must be
     81 recreated.
     82 If the activity is destroyed and the same instance must be recreated, the system passes the state
     83 data defined at (1) to both the {@link android.app.Activity#onCreate onCreate()} method
     84 (2) and the {@link android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} method
     85 (3).</p>
     86 
     87 
     88 
     89 <h2 id="SaveState">Save Your Activity State</h2>
     90 
     91 <p>As your activity begins to stop, the system calls {@link android.app.Activity#onSaveInstanceState
     92 onSaveInstanceState()} so your activity can save state information with a collection of key-value
     93 pairs. The default implementation of this method saves information about the state of the activity's
     94 view hierarchy, such as the text in an {@link android.widget.EditText} widget or the scroll position
     95 of a {@link android.widget.ListView}.</p>
     96 
     97 <p>To save additional state information for your activity, you must
     98 implement {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} and add
     99 key-value pairs to the {@link android.os.Bundle} object. For example:</p>
    100 
    101 <pre>
    102 static final String STATE_SCORE = "playerScore";
    103 static final String STATE_LEVEL = "playerLevel";
    104 ...
    105 
    106 &#64;Override
    107 public void onSaveInstanceState(Bundle savedInstanceState) {
    108     // Save the user's current game state
    109     savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    110     savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
    111     
    112     // Always call the superclass so it can save the view hierarchy state
    113     super.onSaveInstanceState(savedInstanceState);
    114 }
    115 </pre>
    116 
    117 <p class="caution"><strong>Caution:</strong> Always call the superclass implementation of {@link
    118 android.app.Activity#onSaveInstanceState onSaveInstanceState()} so the default implementation
    119 can save the state of the view hierarchy.</p>
    120 
    121 
    122 
    123 <h2 id="RestoreState">Restore Your Activity State</h2>
    124 
    125 <p>When your activity is recreated after it was previously destroyed, you can recover your saved
    126 state from the {@link android.os.Bundle} that the system
    127 passes your activity. Both the {@link android.app.Activity#onCreate onCreate()} and {@link
    128 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} callback methods receive
    129 the same {@link android.os.Bundle} that contains the instance state information.</p>
    130 
    131 <p>Because the {@link android.app.Activity#onCreate onCreate()} method is called whether the
    132 system is creating a new instance of your activity or recreating a previous one, you must check
    133 whether the state {@link android.os.Bundle} is null before you attempt to read it. If it is null,
    134 then the system is creating a new instance of the activity, instead of restoring a previous one
    135 that was destroyed.</p>
    136 
    137 <p>For example, here's how you can restore some state data in {@link android.app.Activity#onCreate
    138 onCreate()}:</p>
    139 
    140 <pre>
    141 &#64;Override
    142 protected void onCreate(Bundle savedInstanceState) {
    143     super.onCreate(savedInstanceState); // Always call the superclass first
    144    
    145     // Check whether we're recreating a previously destroyed instance
    146     if (savedInstanceState != null) {
    147         // Restore value of members from saved state
    148         mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    149         mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    150     } else {
    151         // Probably initialize members with default values for a new instance
    152     }
    153     ...
    154 }
    155 </pre>
    156 
    157 <p>Instead of restoring the state during {@link android.app.Activity#onCreate onCreate()} you
    158 may choose to implement {@link
    159 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}, which the system calls
    160 after the {@link android.app.Activity#onStart()} method. The system calls {@link
    161 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} only if there is a saved
    162 state to restore, so you do not need to check whether the {@link android.os.Bundle} is null:</p>
    163         
    164 <pre>
    165 public void onRestoreInstanceState(Bundle savedInstanceState) {
    166     // Always call the superclass so it can restore the view hierarchy
    167     super.onRestoreInstanceState(savedInstanceState);
    168    
    169     // Restore state members from saved instance
    170     mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    171     mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    172 }
    173 </pre>
    174 
    175 <p class="caution"><strong>Caution:</strong> Always call the superclass implementation of {@link
    176 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} so the default implementation
    177 can restore the state of the view hierarchy.</p>
    178 
    179 <p>To learn more about recreating your activity due to a
    180 restart event at runtime (such as when the screen rotates), read <a
    181 href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a>.</p>
    182 
    183