Handling Runtime changes from google

HandlingRuntimeChanges

Some device configurations can change duringruntime (such as screen orientation, keyboard availability, and language). Whensuch a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate()). The restart behavior is designed to helpyour application adapt to new configurations by automatically reloading yourapplication with alternative resources that match the new device configuration.

To properly handle a restart, it isimportant that your activity restores its previous state through the normal Activity lifecycle, in which Android calls onSaveInstanceState() before it destroys your activity so thatyou can save data about the application state. You can then restore the stateduring onCreate() or onRestoreInstanceState().

To test that your application restartsitself with the application state intact, you should invoke configurationchanges (such as changing the screen orientation) while performing varioustasks in your application. Your application should be able to restart at anytime without loss of user data or state in order to handle events such asconfiguration changes or when the user receives an incoming phone call and thenreturns to your application much later after your application process may havebeen destroyed. To learn how you can restore your activity state, read aboutthe Activity lifecycle.

However, you might encounter a situation inwhich restarting your application and restoring significant amounts of data canbe costly and create a poor user experience. In such a situation, you have twoother options:

a.      Retain an object during aconfiguration change

Allow your activity to restart when a configuration changes, but carry astateful object to the new instance of your activity.

b.      Handle the configuration changeyourself

Prevent the system from restarting your activity during certainconfiguration changes, but receive a callback when the configurations do change,so that you can manually update your activity as necessary.

Retaining an Object Duringa Configuration Change


If restarting your activity requires thatyou recover large sets of data, re-establish a network connection, or performother intensive operations, then a full restart due to a configuration changemight be a slow user experience. Also, it might not be possible for you tocompletely restore your activity state with the Bundle that the system saves for you with the onSaveInstanceState() callback—it is not designed to carry largeobjects (such as bitmaps) and the data within it must be serialized thendeserialized, which can consume a lot of memory and make the configurationchange slow. In such a situation, you can alleviate the burden ofreinitializing your activity by retaining a Fragment when your activity is restarted due to aconfiguration change. This fragment can contain references to stateful objectsthat you want to retain.

When the Android system shuts down youractivity due to a configuration change, the fragments of your activity that youhave marked to retain are not destroyed. You can add such fragments to youractivity to preserve stateful objects.

To retain stateful objects in a fragmentduring a runtime configuration change:

1.      Extend the Fragment class and declare references to yourstateful objects.

2.      Call setRetainInstance(boolean) when the fragment is created.

3.      Add the fragment to your activity.

4.      Use FragmentManager to retrieve the fragment when the activityis restarted.

For example, define your fragment asfollows:

public class RetainedFragment extendsFragment {

    // data object we want to retain
    private MyDataObject data;

    // this method is only called once for this fragment
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // retain this fragment
        setRetainInstance(true);
    }

    public void setData(MyDataObject data) {
        this.data = data;
    }

    public MyDataObject getData() {
        return data;
    }
}

Caution: While you can store any object, you shouldnever pass an object that is tied to the Activity, such as a Drawable, an Adapter, a View or any other object that's associated witha Context. If you do, it will leak all the views andresources of the original activity instance. (Leaking resources means that yourapplication maintains a hold on them and they cannot be garbage-collected, solots of memory can be lost.)

Then use FragmentManager to add the fragment to the activity. Youcan obtain the data object from the fragment when the activity starts againduring runtime configuration changes. For example, define your activity asfollows:

public class MyActivity extends Activity {

    private RetainedFragment dataFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // find the retained fragment on activity restarts
        FragmentManager fm = getFragmentManager();
        dataFragment = (DataFragment)fm.findFragmentByTag(“data”);

        // create the fragment and data the first time
        if (dataFragment == null) {
            // add the fragment
            dataFragment = new DataFragment();
           fm.beginTransaction().add(dataFragment, “data”).commit();
            // load the data from the web
            dataFragment.setData(loadMyData());
        }

        // the data is available in dataFragment.getData()
        ...
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // store the data in the fragment
        dataFragment.setData(collectMyLoadedData());
    }
}

In this example, onCreate() adds a fragment or restores a reference toit. onCreate() also stores the stateful object inside thefragment instance. onDestroy() updates the stateful object inside theretained fragment instance.

Handling the ConfigurationChange Yourself


If your application doesn't need to updateresources during a specific configuration change and you have a performance limitation thatrequires you to avoid the activity restart, then you can declare that youractivity handles the configuration change itself, which prevents the systemfrom restarting your activity.

Note: Handling the configuration change yourselfcan make it much more difficult to use alternative resources, because thesystem does not automatically apply them for you. This technique should beconsidered a last resort when you must avoid restarts due to a configurationchange and is not recommended for most applications.

To declare that your activity handles aconfiguration change, edit the appropriate <activity> element in your manifest file to includethe android:configChanges attribute with a value that represents theconfiguration you want to handle. Possible values are listed in thedocumentation for the android:configChanges attribute (the most commonly used valuesare "orientation" to prevent restarts when the screen orientation changes and "keyboardHidden" to prevent restarts when the keyboardavailability changes). You can declare multiple configuration values in theattribute by separating them with a pipe | character.

For example, the following manifest codedeclares an activity that handles both the screen orientation change andkeyboard availability change:

<activityandroid:name=".MyActivity"
         android:configChanges="orientation|keyboardHidden"
         android:label="@string/app_name">

Now, when one of these configurationschange, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new deviceconfiguration. By reading fields in the Configuration, you can determine the new configurationand make appropriate changes by updating the resources used in your interface.At the time this method is called, your activity's Resources object is updated to return resources basedon the new configuration, so you can easily reset elements of your UI withoutthe system restarting your activity.

Caution: Beginning with Android 3.2 (API level 13), the"screen size" also changes when the device switches between portrait and landscapeorientation. Thus, if you want to prevent runtime restarts due to orientationchange when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must decalare android:configChanges="orientation|screenSize". However, if your application targets APIlevel 12 or lower, then your activity always handles this configuration changeitself (this configuration change does not restart your activity, even whenrunning on an Android 3.2 or higher device).

For example, the following onConfigurationChanged() implementation checks the current deviceorientation:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
        Toast.makeText(this, "landscape",Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation ==Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait",Toast.LENGTH_SHORT).show();
    }
}

The Configuration object represents all of the currentconfigurations, not just the ones that have changed. Most of the time, youwon't care exactly how the configuration has changed and can simply re-assignall your resources that provide alternatives to the configuration that you'rehandling. For example, because the Resources object is now updated, you can reset any ImageViews with setImageResource() and the appropriate resource for the newconfiguration is used (as described in Providing Resources).

Notice that the values from the Configuration fields are integers that are matched tospecific constants from the Configuration class. For documentation about whichconstants to use with each field, refer to the appropriate field in the Configuration reference.

Remember: When you declare your activity to handle aconfiguration change, you are responsible for resetting any elements for whichyou provide alternatives. If you declare your activity to handle theorientation change and have images that should change between landscape andportrait, you must re-assign each resource to each element during onConfigurationChanged().

If you don't need to update your applicationbased on these configuration changes, you can instead not implement onConfigurationChanged(). In which case, all of the resources usedbefore the configuration change are still used and you've only avoided therestart of your activity. However, your application should always be able toshutdown and restart with its previous state intact, so you should not considerthis technique an escape from retaining your state during normal activitylifecycle. Not only because there are other configuration changes that youcannot prevent from restarting your application, but also because you shouldhandle events such as when the user leaves your application and it getsdestroyed before the user returns to it.

For more about which configuration changesyou can handle in your activity, see the android:configChanges documentation and the Configuration class.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值