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