Handling configuration changes when Android programs are running

Source: Internet
Author: User

This article is translated from the official Android document handling Runtime changes, there are translation errors please leave a message to inform, thank you.

The configuration of the device during the operation of the Android program is likely to change (such as the orientation of the screen, keyboard availability, and language, etc.). When these configurations change, Android restarts the running activity (call Ondestory () first, followed by the call to OnCreate ()). This design is designed to allow your program to use different resources to automatically adapt to the new configuration machine when the configuration is changed.

A very important thing to do with the correct restart is to restore the previous state through the activity's normal life cycle, and you can call Onsaveinstancestate () to save the state of the program before the Android destroys your activity. You can then restore the state of the program before the OnCreate () or onrestoreinstancestate () call.

If you want to test the state integrity of your program after it restarts, you can actively change the configuration (such as changing the orientation of the screen) while the program is working on different threads. Your program should restart at any time without losing the user's State or data, such as configuration changes or the process of the user receiving a call after the program is destroyed. You can read about the activity life cycle to learn how to keep your activity state.

However, you may have experienced a bad user experience when you need to recover a large amount of data during a program restart. In this case, you have the following two methods:

    1. Preserve an object when configuration changes
      Allow your activity to restart when configuration changes, and then bring a class with all of the previous state data when you create a new activity

    2. You handle configuration changes yourself
      Instead of restarting your activity, you receive a callback method so that you can update the resources that the activity needs to update

Save an object when configuration changes

If restarting your activity requires recovering large amounts of data, rebuilding network connections, or showing other urgent transactions, restarting will be very slow. At the same time, you cannot save the entire activity's state data into the bundle when the system callback Onsaveinstancestate (), nor is it designed to carry large data objects (such as bitmap objects) that need to be serialized and deserialized. That would cost a lot of memory and slow down configuration changes. In this case, you can save a fragment to mitigate the initial burden of the activity restart due to configuration changes. This fragment can hold the reference you want to save into a state object.

When the Android system destroys your activity because of configuration changes, the fragment that you want to save the data in the activity will not be destroyed. You can add such fragment to the activity to protect the state object.

To save a state object during configuration changes:

    1. Inherit the fragment class and declare your state reference
    2. The Setretaininstance (Boolean) method is called when fragment is created
    3. Put the above fragment in your activity.
    4. Use Fragmentmanager to save this fragment when the activity restarts

For example, the following example:

public class RetainedFragment extends Fragment { //我们想要的保存的数据对象 private MyDataObject data; // 这个方法在fragment里只被调用一次 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 保存这个fragment setRetainInstance(true); } public void setData(MyDataObject data) { this.data = data; } public MyDataObject getData() { return data; } } 

Caution: When you save any object, it is best not to save objects that are bound to the activity, such as drawable, Adapter, view, or any object that needs to be bound with the context. If you save, it means that you will leak all views and resources in the original activity entity. (Leaking resources means that your program holds these objects so that they can't be garbage collected, causing a memory leak.) )

Then use Fragmentmanager to put the above fragment in the activity. You can get data objects from fragment during activity restart. Examples of activity are as follows:

 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"); First create fragment and data if (datafragment = = null) {//Add the Fragment datafragment = new Dataf Ragment (); 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 (); Save the data in this fragment Datafragment.setdata (Collectmyloadeddata ()); } }

In the example above, OnCreate () creates a fragment object and holds the data object inside it. The data objects in the fragment are then updated within the Ondestory () method.

You handle configuration changes yourself

If your program does not need to update resources during some configuration changes, and you have some special restrictions that prevent you from restarting your activity, you can declare yourself to handle configuration changes and the system will not restart your activity.

Note: Handling configuration changes yourself becomes more difficult when you use other resources because the system does not automatically handle it for you. You should use this technique only when you have to, most of the programs are deprecated.

You can declare the Android:configchanges property in the corresponding tab of the Mainifest file to configure the event you want to handle. The Adnroid:configchanges document lists all the properties that can be configured (most people use "orientation" to avoid activity restarts due to changes in screen orientation, and "Keyboardhidden" To prevent a change in the keyboard's usability and cause a reboot). You can use ' | ' A character separates different properties to declare multiple configurations.

For example, the following configuration causes MyActivity to detect screen orientation changes and keyboard availability changes:

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

Now, when the two configurations above change, myactivity will not restart. However, MyActivity's onconfigurationchanged () method is called. This method uses a configuration object to specify the parameters for the new device. By reading the property values of the configuration, you can determine the new configuration and update it with your interface to the appropriate resources. When this method is called, your activity's resource object will be updated based on the new configuration, so you can easily reset your user view without restarting the activity.

Note: Starting with Andorid 3.2 (API level 13), the screen size will change when the device's screen is switched vertically and horizontally. So from API level 13 (there are declarations minsdkversion and targetsdkversion attributes in mainifest), if you want to avoid activity restarting at run time, you need to be in the Configchanges attribute, in addition to declaring "Orientation" plus "screensize", such as android:configchanges= "Orientation|screensize". However, if your program's target API is 12 or below, your activity can also use these two properties to avoid restarting (this two property avoids all Android versions of the reboot due to changes in the screen orientation).

For example, the following onconfigurationchanged () method can be used to detect the current device screen change:

@Override public void onConfigurationChanged(Configuration newConfig) {     super.onConfigurationChanged(newConfig);     // 检查屏幕的方向    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 holds the configurations of all current devices, not just those that change. Usually, you don't have to worry about how the configuration changes, you just get the configuration from the Config and reassign all of your resource files. For example, because the resource object is now updated, you can use the Setimageresource () method to reset all of your ImageView controls (resource files can refer to providing resources).

It is important to note that the parameters in the configuration object are all shaped, and they match the constants in the Cofiguration class. You can find the available configuration properties from your configuration document.

Remember: When you declare that you are dealing with configuration changes, it is your responsibility to update the elements that have alternatives. If you declare your activity to handle screen orientation events, and you have some images that need to be changed at the vertical and horizontal screen, you must reset those control resources during the Onconfiguration () method call.

If you don't have to update your program when you need to reconfigure the changes, you can also not implement the Onconfigurationchanged () method. In this case, the program will continue to reference the previous resource after the configuration changes, but do not restart your activity. However, your program is best to be destroyed and restarted with the previous state, and you should not use this technique to keep your state from slipping through the normal life cycle. It's not just that you can't avoid the changes you're not dealing with that will cause your program to restart, and you should handle the event that the user left your program and destroy it before the user returns.

If you want to know how many configuration changes in the activity can be handled, look at the Android:configchanges and configuration classes.

I found CSDN is not very good for markdown writing articles, and if you want to get a better reading experience, you can visit this link to read.

Handling configuration changes when Android programs are running

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.