1page.title=Recreating an Activity
2page.tags=activity lifecycle
3helpoutsWidget=true
4
5trainingnavtop=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
21Different Screens</a></li>
22      <li><a
23href="{@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
32when the user presses the <em>Back</em> button or your activity signals its own destruction by
33calling {@link android.app.Activity#finish()}. The system may also destroy your activity if it's
34currently stopped and hasn't been used in a long time or the foreground activity requires more
35resources 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
38itself, the system's concept of that {@link android.app.Activity} instance is gone forever because
39the behavior indicates the activity is no longer needed. However, if the system destroys
40the 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
42the user navigates back to it, the system creates a new instance of the activity using a set of
43saved data that describes the state of the activity when it was destroyed. The saved data that the
44system uses to restore the previous state is called the "instance state" and is a collection of
45key-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
48the user rotates the screen. When the screen changes orientation, the system destroys and recreates
49the foreground activity because the screen configuration has changed and your activity might need to
50load 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
53about each {@link android.view.View} object in your activity layout (such as the text value entered
54into an {@link android.widget.EditText} object). So, if your activity instance is destroyed and
55recreated, the state of the layout is restored to its previous state with no
56code required by you. However, your
57activity might have more state information that you'd like to restore, such as member variables that
58track 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
61the 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
63android:id}</a> attribute.</p>
64
65<p>To save additional data about the activity state, you must override
66the {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} callback method.
67The system calls this method when the user is leaving your activity
68and passes it the {@link android.os.Bundle} object that will be saved in the
69event that your activity is destroyed unexpectedly. If
70the system must recreate the activity instance later, it passes the same {@link
71android.os.Bundle} object to both the {@link android.app.Activity#onRestoreInstanceState
72onRestoreInstanceState()} and {@link android.app.Activity#onCreate onCreate()}
73methods.</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
77calls {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} (1) so you can specify
78additional state data you'd like to save in case the {@link android.app.Activity} instance must be
79recreated.
80If the activity is destroyed and the same instance must be recreated, the system passes the state
81data 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
90onSaveInstanceState()} so your activity can save state information with a collection of key-value
91pairs. The default implementation of this method saves information about the state of the activity's
92view hierarchy, such as the text in an {@link android.widget.EditText} widget or the scroll position
93of a {@link android.widget.ListView}.</p>
94
95<p>To save additional state information for your activity, you must
96implement {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} and add
97key-value pairs to the {@link android.os.Bundle} object. For example:</p>
98
99<pre>
100static final String STATE_SCORE = "playerScore";
101static final String STATE_LEVEL = "playerLevel";
102...
103
104&#64;Override
105public 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
116android.app.Activity#onSaveInstanceState onSaveInstanceState()} so the default implementation
117can 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
124state from the {@link android.os.Bundle} that the system
125passes your activity. Both the {@link android.app.Activity#onCreate onCreate()} and {@link
126android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} callback methods receive
127the 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
130system is creating a new instance of your activity or recreating a previous one, you must check
131whether the state {@link android.os.Bundle} is null before you attempt to read it. If it is null,
132then the system is creating a new instance of the activity, instead of restoring a previous one
133that was destroyed.</p>
134
135<p>For example, here's how you can restore some state data in {@link android.app.Activity#onCreate
136onCreate()}:</p>
137
138<pre>
139&#64;Override
140protected 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
156may choose to implement {@link
157android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}, which the system calls
158after the {@link android.app.Activity#onStart()} method. The system calls {@link
159android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} only if there is a saved
160state to restore, so you do not need to check whether the {@link android.os.Bundle} is null:</p>
161
162<pre>
163public 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
174android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} so the default implementation
175can restore the state of the view hierarchy.</p>
176
177<p>To learn more about recreating your activity due to a
178restart event at runtime (such as when the screen rotates), read <a
179href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a>.</p>
180
181