blob: d074873f069e6cd69d37e7983fb5c35bd3c27591 [file] [log] [blame]
Scott Mainf940a1f2010-02-09 18:48:27 -08001page.title=Handling Runtime Changes
Scott Main64461bf2013-04-11 19:32:08 -07002page.tags="activity","lifecycle"
Scott Mainf940a1f2010-02-09 18:48:27 -08003@jd:body
4
5<div id="qv-wrapper">
6<div id="qv">
7
8 <h2>In this document</h2>
9 <ol>
Scott Mainc6cb8a72010-04-09 15:52:18 -070010 <li><a href="#RetainingAnObject">Retaining an Object During a Configuration Change</a></li>
Scott Mainf940a1f2010-02-09 18:48:27 -080011 <li><a href="#HandlingTheChange">Handling the Configuration Change Yourself</a>
12 </ol>
13
14 <h2>See also</h2>
15 <ol>
16 <li><a href="providing-resources.html">Providing Resources</a></li>
17 <li><a href="accessing-resources.html">Accessing Resources</a></li>
Scott Mainf284d492012-07-31 09:46:52 -070018 <li><a href="http://android-developers.blogspot.com/2009/02/faster-screen-orientation-change.html">Faster
19 Screen Orientation Change</a></li>
Scott Mainf940a1f2010-02-09 18:48:27 -080020 </ol>
21</div>
22</div>
23
24<p>Some device configurations can change during runtime
25(such as screen orientation, keyboard availability, and language). When such a change occurs,
Scott Mainc6cb8a72010-04-09 15:52:18 -070026Android restarts the running
Scott Main8da11912011-08-12 12:22:18 -070027{@link android.app.Activity} ({@link android.app.Activity#onDestroy()} is called, followed by {@link
Scott Mainc6cb8a72010-04-09 15:52:18 -070028android.app.Activity#onCreate(Bundle) onCreate()}). The restart behavior is designed to help your
29application adapt to new configurations by automatically reloading your application with
Scott Main8da11912011-08-12 12:22:18 -070030alternative resources that match the new device configuration.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -080031
Scott Main8da11912011-08-12 12:22:18 -070032<p>To properly handle a restart, it is important that your activity restores its previous
Scott Main9bf45a02011-02-03 18:46:45 -080033state through the normal <a
Scott Main50e990c2012-06-21 17:14:39 -070034href="{@docRoot}guide/components/activities.html#Lifecycle">Activity
Scott Mainc6cb8a72010-04-09 15:52:18 -070035lifecycle</a>, in which Android calls
36{@link android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} before it destroys
Scott Main8da11912011-08-12 12:22:18 -070037your activity so that you can save data about the application state. You can then restore the state
Scott Mainc6cb8a72010-04-09 15:52:18 -070038during {@link android.app.Activity#onCreate(Bundle) onCreate()} or {@link
Scott Main8da11912011-08-12 12:22:18 -070039android.app.Activity#onRestoreInstanceState(Bundle) onRestoreInstanceState()}.</p>
Scott Mainc6cb8a72010-04-09 15:52:18 -070040
Scott Main8da11912011-08-12 12:22:18 -070041<p>To test that 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. Your application should be able to restart at any time without loss of
44user data or state in order to handle events such as configuration changes or when the user receives
45an incoming phone call and then returns to your application much later after your application
46process may have been destroyed. To learn how you can restore your activity state, read about the <a
Scott Main50e990c2012-06-21 17:14:39 -070047href="{@docRoot}guide/components/activities.html#Lifecycle">Activity lifecycle</a>.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -080048
49<p>However, you might encounter a situation in which restarting your application and
Scott Mainc6cb8a72010-04-09 15:52:18 -070050restoring significant amounts of data can be costly and create a poor user experience. In such a
Scott Main8da11912011-08-12 12:22:18 -070051situation, you have two other options:</p>
Scott Mainf940a1f2010-02-09 18:48:27 -080052
53<ol type="a">
Scott Main369c1c12010-12-07 11:17:00 -080054 <li><a href="#RetainingAnObject">Retain an object during a configuration change</a>
Scott Main8da11912011-08-12 12:22:18 -070055 <p>Allow your activity to restart when a configuration changes, but carry a stateful
Ricardo Cervera893ee422014-01-27 17:47:39 -080056object to the new instance of your activity.</p>
Scott Mainc6cb8a72010-04-09 15:52:18 -070057
Scott Mainf940a1f2010-02-09 18:48:27 -080058 </li>
Scott Mainc6cb8a72010-04-09 15:52:18 -070059 <li><a href="#HandlingTheChange">Handle the configuration change yourself</a>
Scott Main8da11912011-08-12 12:22:18 -070060 <p>Prevent the system from restarting your activity during certain configuration
61changes, but receive a callback when the configurations do change, so that you can manually update
62your activity as necessary.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -080063 </li>
64</ol>
65
Scott Mainf940a1f2010-02-09 18:48:27 -080066
Scott Mainc6cb8a72010-04-09 15:52:18 -070067<h2 id="RetainingAnObject">Retaining an Object During a Configuration Change</h2>
Scott Mainf940a1f2010-02-09 18:48:27 -080068
Scott Main8da11912011-08-12 12:22:18 -070069<p>If restarting your activity requires that you recover large sets of data, re-establish a network
70connection, or perform other intensive operations, then a full restart due to a configuration change
71might be a slow user experience. Also, it might not be possible for you to completely restore your
72activity state with the {@link android.os.Bundle} that the system saves for you with the {@link
73android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} callback&mdash;it is not
74designed to carry large objects (such as bitmaps) and the data within it must be serialized then
75deserialized, which can consume a lot of memory and make the configuration change slow. In such a
Ricardo Cervera893ee422014-01-27 17:47:39 -080076situation, you can alleviate the burden of reinitializing your activity by retaining a {@link
77android.app.Fragment} when your activity is restarted due to a configuration change. This fragment
78can contain references to stateful objects that you want to retain.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -080079
Ricardo Cervera893ee422014-01-27 17:47:39 -080080<p>When the Android system shuts down your activity due to a configuration change, the fragments
81of your activity that you have marked to retain are not destroyed. You can add such fragments to
82your activity to preserve stateful objects.</p>
83
84<p>To retain stateful objects in a fragment during a runtime configuration change:</p>
85
Scott Mainc6cb8a72010-04-09 15:52:18 -070086<ol>
Ricardo Cervera893ee422014-01-27 17:47:39 -080087 <li>Extend the {@link android.app.Fragment} class and declare references to your stateful
88 objects.</li>
89 <li>Call {@link android.app.Fragment#setRetainInstance(boolean)} when the fragment is created.
90 </li>
91 <li>Add the fragment to your activity.</li>
92 <li>Use {@link android.app.FragmentManager} to retrieve the fragment when the activity is
93 restarted.</li>
Scott Mainc6cb8a72010-04-09 15:52:18 -070094</ol>
95
Ricardo Cervera893ee422014-01-27 17:47:39 -080096<p>For example, define your fragment as follows:</p>
Scott Mainf940a1f2010-02-09 18:48:27 -080097
98<pre>
Ricardo Cervera893ee422014-01-27 17:47:39 -080099public class RetainedFragment extends Fragment {
100
101 // data object we want to retain
102 private MyDataObject data;
103
104 // this method is only called once for this fragment
105 &#64;Override
106 public void onCreate(Bundle savedInstanceState) {
107 super.onCreate(savedInstanceState);
108 // retain this fragment
109 setRetainInstance(true);
110 }
111
112 public void setData(MyDataObject data) {
113 this.data = data;
114 }
115
116 public MyDataObject getData() {
117 return data;
118 }
Scott Mainf940a1f2010-02-09 18:48:27 -0800119}
120</pre>
121
Ricardo Cervera893ee422014-01-27 17:47:39 -0800122<p class="caution"><strong>Caution:</strong> While you can store any object, you
Scott Mainf940a1f2010-02-09 18:48:27 -0800123should never pass an object that is tied to the {@link android.app.Activity}, such as a {@link
124android.graphics.drawable.Drawable}, an {@link android.widget.Adapter}, a {@link android.view.View}
125or any other object that's associated with a {@link android.content.Context}. If you do, it will
Scott Main8da11912011-08-12 12:22:18 -0700126leak all the views and resources of the original activity instance. (Leaking resources
Scott Mainf940a1f2010-02-09 18:48:27 -0800127means that your application maintains a hold on them and they cannot be garbage-collected, so
128lots of memory can be lost.)</p>
129
Ricardo Cervera893ee422014-01-27 17:47:39 -0800130<p>Then use {@link android.app.FragmentManager} to add the fragment to the activity.
131You can obtain the data object from the fragment when the activity starts again during runtime
132configuration changes. For example, define your activity as follows:</p>
Scott Mainf940a1f2010-02-09 18:48:27 -0800133
134<pre>
Ricardo Cervera893ee422014-01-27 17:47:39 -0800135public class MyActivity extends Activity {
Scott Mainf940a1f2010-02-09 18:48:27 -0800136
Ricardo Cervera893ee422014-01-27 17:47:39 -0800137 private RetainedFragment dataFragment;
138
139 &#64;Override
140 public void onCreate(Bundle savedInstanceState) {
141 super.onCreate(savedInstanceState);
142 setContentView(R.layout.main);
143
144 // find the retained fragment on activity restarts
145 FragmentManager fm = getFragmentManager();
146 dataFragment = (DataFragment) fm.findFragmentByTag(“data”);
147
148 // create the fragment and data the first time
149 if (dataFragment == null) {
150 // add the fragment
151 dataFragment = new DataFragment();
152 fm.beginTransaction().add(dataFragment, “data”).commit();
153 // load the data from the web
154 dataFragment.setData(loadMyData());
155 }
156
157 // the data is available in dataFragment.getData()
158 ...
Scott Mainf940a1f2010-02-09 18:48:27 -0800159 }
Ricardo Cervera893ee422014-01-27 17:47:39 -0800160
161 &#64;Override
162 public void onDestroy() {
163 super.onDestroy();
164 // store the data in the fragment
165 dataFragment.setData(collectMyLoadedData());
166 }
Scott Mainf940a1f2010-02-09 18:48:27 -0800167}
168</pre>
169
Ricardo Cervera893ee422014-01-27 17:47:39 -0800170<p>In this example, {@link android.app.Activity#onCreate(Bundle) onCreate()} adds a fragment
171or restores a reference to it. {@link android.app.Activity#onCreate(Bundle) onCreate()} also
172stores the stateful object inside the fragment instance.
173{@link android.app.Activity#onDestroy() onDestroy()} updates the stateful object inside the
174retained fragment instance.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -0800175
176
177
178
179
180<h2 id="HandlingTheChange">Handling the Configuration Change Yourself</h2>
181
182<p>If your application doesn't need to update resources during a specific configuration
183change <em>and</em> you have a performance limitation that requires you to
Scott Main8da11912011-08-12 12:22:18 -0700184avoid the activity restart, then you can declare that your activity handles the configuration change
185itself, which prevents the system from restarting your activity.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -0800186
187<p class="note"><strong>Note:</strong> Handling the configuration change yourself can make it much
Scott Mainc6cb8a72010-04-09 15:52:18 -0700188more difficult to use alternative resources, because the system does not automatically apply them
Scott Main8da11912011-08-12 12:22:18 -0700189for you. This technique should be considered a last resort when you must avoid restarts due to a
190configuration change and is not recommended for most applications.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -0800191
Scott Main8da11912011-08-12 12:22:18 -0700192<p>To declare that your activity handles a configuration change, edit the appropriate <a
193href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a> element in
194your manifest file to include the <a
Scott Mainf940a1f2010-02-09 18:48:27 -0800195href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
Scott Main8da11912011-08-12 12:22:18 -0700196android:configChanges}</a> attribute with a value that represents the configuration you want to
197handle. Possible values are listed in the documentation for the <a
198href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
199android:configChanges}</a> attribute (the most commonly used values are {@code "orientation"} to
200prevent restarts when the screen orientation changes and {@code "keyboardHidden"} to prevent
201restarts when the keyboard availability changes). You can declare multiple configuration values in
202the attribute by separating them with a pipe {@code |} character.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -0800203
Scott Main8da11912011-08-12 12:22:18 -0700204<p>For example, the following manifest code declares an activity that handles both the
Scott Mainf940a1f2010-02-09 18:48:27 -0800205screen orientation change and keyboard availability change:</p>
206
207<pre>
208&lt;activity android:name=".MyActivity"
209 android:configChanges="orientation|keyboardHidden"
210 android:label="@string/app_name">
211</pre>
212
Scott Main8da11912011-08-12 12:22:18 -0700213<p>Now, when one of these configurations change, {@code MyActivity} does not restart.
214Instead, the {@code MyActivity} receives a call to {@link
Scott Mainf940a1f2010-02-09 18:48:27 -0800215android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}. This method
216is passed a {@link android.content.res.Configuration} object that specifies
217the new device configuration. By reading fields in the {@link android.content.res.Configuration},
218you can determine the new configuration and make appropriate changes by updating
219the resources used in your interface. At the
Scott Main8da11912011-08-12 12:22:18 -0700220time this method is called, your activity's {@link android.content.res.Resources} object is updated
Scott Mainf940a1f2010-02-09 18:48:27 -0800221to return resources based on the new configuration, so you can easily
Scott Main8da11912011-08-12 12:22:18 -0700222reset elements of your UI without the system restarting your activity.</p>
223
224<p class="caution"><strong>Caution:</strong> Beginning with Android 3.2 (API level 13), <strong>the
225"screen size" also changes</strong> when the device switches between portrait and landscape
226orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing
227for API level 13 or higher (as declared by the <a
228href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> and <a
229href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a>
230attributes), you must include the {@code "screenSize"} value in addition to the {@code
231"orientation"} value. That is, you must decalare {@code
232android:configChanges="orientation|screenSize"}. However, if your application targets API level
23312 or lower, then your activity always handles this configuration change itself (this configuration
234change does not restart your activity, even when running on an Android 3.2 or higher device).</p>
Scott Mainf940a1f2010-02-09 18:48:27 -0800235
236<p>For example, the following {@link
237android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()} implementation
Scott Main8da11912011-08-12 12:22:18 -0700238checks the current device orientation:</p>
Scott Mainf940a1f2010-02-09 18:48:27 -0800239
240<pre>
241&#64;Override
242public void onConfigurationChanged(Configuration newConfig) {
243 super.onConfigurationChanged(newConfig);
244
245 // Checks the orientation of the screen
246 if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
247 Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
248 } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
249 Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
250 }
Scott Mainf940a1f2010-02-09 18:48:27 -0800251}
252</pre>
253
254<p>The {@link android.content.res.Configuration} object represents all of the current
255configurations, not just the ones that have changed. Most of the time, you won't care exactly how
256the configuration has changed and can simply re-assign all your resources that provide alternatives
257to the configuration that you're handling. For example, because the {@link
258android.content.res.Resources} object is now updated, you can reset
Scott Main8da11912011-08-12 12:22:18 -0700259any {@link android.widget.ImageView}s with {@link android.widget.ImageView#setImageResource(int)
260setImageResource()}
Scott Mainf940a1f2010-02-09 18:48:27 -0800261and the appropriate resource for the new configuration is used (as described in <a
262href="providing-resources.html#AlternateResources">Providing Resources</a>).</p>
263
264<p>Notice that the values from the {@link
265android.content.res.Configuration} fields are integers that are matched to specific constants
266from the {@link android.content.res.Configuration} class. For documentation about which constants
267to use with each field, refer to the appropriate field in the {@link
268android.content.res.Configuration} reference.</p>
269
Scott Main8da11912011-08-12 12:22:18 -0700270<p class="note"><strong>Remember:</strong> When you declare your activity to handle a configuration
Scott Mainf940a1f2010-02-09 18:48:27 -0800271change, you are responsible for resetting any elements for which you provide alternatives. If you
Scott Main8da11912011-08-12 12:22:18 -0700272declare your activity to handle the orientation change and have images that should change
Scott Mainf940a1f2010-02-09 18:48:27 -0800273between landscape and portrait, you must re-assign each resource to each element during {@link
274android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}.</p>
275
276<p>If you don't need to update your application based on these configuration
277changes, you can instead <em>not</em> implement {@link
278android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}. In
279which case, all of the resources used before the configuration change are still used
Scott Main8da11912011-08-12 12:22:18 -0700280and you've only avoided the restart of your activity. However, your application should always be
281able to shutdown and restart with its previous state intact, so you should not consider this
282technique an escape from retaining your state during normal activity lifecycle. Not only because
283there are other configuration changes that you cannot prevent from restarting your application, but
284also because you should handle events such as when the user leaves your application and it gets
285destroyed before the user returns to it.</p>
Scott Mainf940a1f2010-02-09 18:48:27 -0800286
Scott Main8da11912011-08-12 12:22:18 -0700287<p>For more about which configuration changes you can handle in your activity, see the <a
Scott Mainf940a1f2010-02-09 18:48:27 -0800288href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
289android:configChanges}</a> documentation and the {@link android.content.res.Configuration}
290class.</p>