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