runtime-changes.jd revision 9bf45a00752f84037dcf1aba79e76542b4d4ed22
1page.title=Handling Runtime Changes
2parent.title=Application Resources
3parent.link=index.html
4@jd:body
5
6<div id="qv-wrapper">
7<div id="qv">
8
9  <h2>In this document</h2>
10  <ol>
11    <li><a href="#RetainingAnObject">Retaining an Object During a Configuration Change</a></li>
12    <li><a href="#HandlingTheChange">Handling the Configuration Change Yourself</a>
13  </ol>
14
15  <h2>See also</h2>
16  <ol>
17    <li><a href="providing-resources.html">Providing Resources</a></li>
18    <li><a href="accessing-resources.html">Accessing Resources</a></li>
19    <li><a href="{@docRoot}resources/articles/faster-screen-orientation-change.html">Faster Screen
20Orientation Change</a></li>
21  </ol>
22</div>
23</div>
24
25<p>Some device configurations can change during runtime
26(such as screen orientation, keyboard availability, and language). When such a change occurs,
27Android restarts the running
28Activity ({@link android.app.Activity#onDestroy()} is called, followed by {@link
29android.app.Activity#onCreate(Bundle) onCreate()}). The restart behavior is designed to help your
30application adapt to new configurations by automatically reloading your application with
31alternative resources.</p>
32
33<p>To properly handle a restart, it is important that your Activity restores its previous
34state through the normal <a
35href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activity
36lifecycle</a>, in which Android calls
37{@link android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} before it destroys
38your Activity so that you can save data about the application state. You can then restore the state
39during {@link android.app.Activity#onCreate(Bundle) onCreate()} or {@link
40android.app.Activity#onRestoreInstanceState(Bundle) onRestoreInstanceState()}. To test
41that your application restarts itself with the application state intact, you should
42invoke configuration changes (such as changing the screen orientation) while performing various
43tasks in your application.</p>
44
45<p>Your application should be able to restart at any time without loss of user data or
46state in order to handle events such as when the user receives an incoming phone call and then
47returns to your application (read about the
48<a href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activity lifecycle</a>).</p>
49
50<p>However, you might encounter a situation in which restarting your application and
51restoring significant amounts of data can be costly and create a poor user experience. In such a
52situation, you have two options:</p>
53
54<ol type="a">
55  <li><a href="#RetainingAnObject">Retain an object during a configuration change</a>
56  <p>Allow your Activity to restart when a configuration changes, but carry a stateful
57{@link java.lang.Object} to the new instance of your Activity.</p>
58
59  </li>
60  <li><a href="#HandlingTheChange">Handle the configuration change yourself</a>
61  <p>Prevent the system from restarting your Activity during certain configuration
62changes and receive a callback when the configurations do change, so that you can manually update
63your Activity as necessary.</p>
64  </li>
65</ol>
66
67
68<h2 id="RetainingAnObject">Retaining an Object During a Configuration Change</h2>
69
70<p>If restarting your Activity requires that you recover large sets of data, re-establish a
71network connection, or perform other intensive operations, then a full restart due to a
72configuration change might
73be an unpleasant user experience. Also, it may not be possible for you to completely
74maintain your Activity state with the {@link android.os.Bundle} that the system saves for you during
75the Activity lifecycle&mdash;it is not designed to carry large objects (such as bitmaps) and the
76data within it must be serialized then deserialized, which can consume a lot of memory and make the
77configuration change slow. In such a situation, you can alleviate the burden of reinitializing
78your Activity by retaining a stateful Object when your Activity is restarted due to a configuration
79change.</p>
80
81<p>To retain an Object during a runtime configuration change:</p>
82<ol>
83  <li>Override the {@link android.app.Activity#onRetainNonConfigurationInstance()} method to return
84the Object you would like to retain.</li>
85  <li>When your Activity is created again, call {@link
86android.app.Activity#getLastNonConfigurationInstance()} to recover your Object.</li>
87</ol>
88
89<p>Android calls {@link android.app.Activity#onRetainNonConfigurationInstance()} between {@link
90android.app.Activity#onStop()} and {@link
91android.app.Activity#onDestroy()} when it shuts down your Activity due to a configuration
92change. In your implementation of {@link
93android.app.Activity#onRetainNonConfigurationInstance()}, you can return any {@link
94java.lang.Object} that you need in order to efficiently restore your state after the configuration
95change.</p>
96
97<p>A scenario in which this can be valuable is if your application loads a lot of data from the
98web. If the user changes the orientation of the device and the Activity restarts, your application
99must re-fetch the data, which could be slow. What you can do instead is implement
100{@link android.app.Activity#onRetainNonConfigurationInstance()} to return an object carrying your
101data and then retrieve the data when your Activity starts again with {@link
102android.app.Activity#getLastNonConfigurationInstance()}. For example:</p>
103
104<pre>
105&#64;Override
106public Object onRetainNonConfigurationInstance() {
107    final MyDataObject data = collectMyLoadedData();
108    return data;
109}
110</pre>
111
112<p class="caution"><strong>Caution:</strong> While you can return any object, you
113should never pass an object that is tied to the {@link android.app.Activity}, such as a {@link
114android.graphics.drawable.Drawable}, an {@link android.widget.Adapter}, a {@link android.view.View}
115or any other object that's associated with a {@link android.content.Context}. If you do, it will
116leak all the Views and resources of the original Activity instance. (To leak the resources
117means that your application maintains a hold on them and they cannot be garbage-collected, so
118lots of memory can be lost.)</p>
119
120<p>Then retrieve the {@code data} when your Activity starts again:</p>
121
122<pre>
123&#64;Override
124public void onCreate(Bundle savedInstanceState) {
125    super.onCreate(savedInstanceState);
126    setContentView(R.layout.main);
127
128    final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
129    if (data == null) {
130        data = loadMyData();
131    }
132    ...
133}
134</pre>
135
136<p>In this case, {@link android.app.Activity#getLastNonConfigurationInstance()} retrieves
137the data saved by {@link android.app.Activity#onRetainNonConfigurationInstance()}. If {@code data}
138is null (which happens when the
139Activity starts due to any reason other than a configuration change) then the data object is loaded
140from the original source.</p>
141
142
143
144
145
146<h2 id="HandlingTheChange">Handling the Configuration Change Yourself</h2>
147
148<p>If your application doesn't need to update resources during a specific configuration
149change <em>and</em> you have a performance limitation that requires you to
150avoid the Activity restart, then you can declare that your Activity handles the configuration change
151itself, which prevents the system from restarting your Activity.</p>
152
153<p class="note"><strong>Note:</strong> Handling the configuration change yourself can make it much
154more difficult to use alternative resources, because the system does not automatically apply them
155for you. This technique should be considered a last resort and is not recommended for most
156applications.</p>
157
158<p>To declare that your Activity handles a configuration change, edit the appropriate <a
159href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a> element
160in your manifest file to include the <a
161href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
162android:configChanges}</a> attribute with a string value that represents the configuration that you
163want to handle. Possible values are listed in the documentation for
164the <a href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
165android:configChanges}</a> attribute (the most commonly used values are {@code orientation} to
166handle when the screen orientation changes and {@code keyboardHidden} to handle when the
167keyboard availability changes).  You can declare multiple configuration values in the attribute
168by separating them with a pipe character ("|").</p>
169
170<p>For example, the following manifest snippet declares an Activity that handles both the
171screen orientation change and keyboard availability change:</p>
172
173<pre>
174&lt;activity android:name=".MyActivity"
175          android:configChanges="orientation|keyboardHidden"
176          android:label="@string/app_name">
177</pre>
178
179<p>Now when one of these configurations change, {@code MyActivity} is not restarted.
180Instead, the Activity receives a call to {@link
181android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}. This method
182is passed a {@link android.content.res.Configuration} object that specifies
183the new device configuration. By reading fields in the {@link android.content.res.Configuration},
184you can determine the new configuration and make appropriate changes by updating
185the resources used in your interface. At the
186time this method is called, your Activity's {@link android.content.res.Resources} object is updated
187to return resources based on the new configuration, so you can easily
188reset elements of your UI without the system restarting your Activity.</p>
189
190<p>For example, the following {@link
191android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()} implementation
192checks the availability of a hardware keyboard and the current device orientation:</p>
193
194<pre>
195&#64;Override
196public void onConfigurationChanged(Configuration newConfig) {
197    super.onConfigurationChanged(newConfig);
198
199    // Checks the orientation of the screen
200    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
201        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
202    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
203        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
204    }
205    // Checks whether a hardware keyboard is available
206    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
207        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
208    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
209        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
210    }
211}
212</pre>
213
214<p>The {@link android.content.res.Configuration} object represents all of the current
215configurations, not just the ones that have changed. Most of the time, you won't care exactly how
216the configuration has changed and can simply re-assign all your resources that provide alternatives
217to the configuration that you're handling. For example, because the {@link
218android.content.res.Resources} object is now updated, you can reset
219any {@link android.widget.ImageView}s with {@link android.widget.ImageView#setImageResource(int)}
220and the appropriate resource for the new configuration is used (as described in <a
221href="providing-resources.html#AlternateResources">Providing Resources</a>).</p>
222
223<p>Notice that the values from the {@link
224android.content.res.Configuration} fields are integers that are matched to specific constants
225from the {@link android.content.res.Configuration} class. For documentation about which constants
226to use with each field, refer to the appropriate field in the {@link
227android.content.res.Configuration} reference.</p>
228
229<p class="note"><strong>Remember:</strong> When you declare your Activity to handle a configuration
230change, you are responsible for resetting any elements for which you provide alternatives. If you
231declare your Activity to handle the orientation change and have images that should change
232between landscape and portrait, you must re-assign each resource to each element during {@link
233android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}.</p>
234
235<p>If you don't need to update your application based on these configuration
236changes, you can instead <em>not</em> implement {@link
237android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}. In
238which case, all of the resources used before the configuration change are still used
239and you've only avoided the restart of your Activity. However, your application should always be
240able to shutdown and restart with its previous state intact. Not only because
241there are other configuration changes that you cannot prevent from restarting your application but
242also in order to handle events such as when the user receives an incoming phone call and then
243returns to your application.</p>
244
245<p>For more about which configuration changes you can handle in your Activity, see the <a
246href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
247android:configChanges}</a> documentation and the {@link android.content.res.Configuration}
248class.</p>
249