Some device configurations can be changed during running (such as screen orientation, keyboard availability, language, etc ). When such a change occurs, Android restarts the running Activity (onDestroy () callback and then calls the onCreate () callback method ). Designing such a restart behavior helps the application restart and reload the optional resources that match the new device configuration.
To properly handle the restart, it is important to restore the previous lifecycle status of the Activity. Therefore, before the Activity is destroyed, Android will call onSaveInstanceState () callback method to save application-related status data. In this way, the previous state can be restored when the onCreate () or onRestoreInstanceState () of the Activity is called.
To test the status integrity after the application is restarted, you should change the device configuration (such as changing the screen direction) when running the program ). The application should be able to restart at any time when handling configuration changes, telephone access, and other events without losing user data and status. To learn how the Activity status is restored, read the lifecycle of the Activity.
However, a large amount of data needs to be restored when the application is restarted, which may lead to poor user experience. In this case, there are two options:
1. Keep an object during configuration change.
When the configuration changes, the Activity can be restarted, but the status object must be carried to the new instance of the Activity.
2. Handle configuration changes by yourself
During a configuration change, the system will not restart the Activity. However, you must receive a callback method when the configuration changes, so that you can manually update the Activity if necessary.
Retain an object during configuration changes
If you want to restore a large dataset, recreate a network connection, or perform other sensitive operations when restarting the Activity, the user experience will be reduced due to configuration changes. In addition, the system cannot use the Bundle object of the onSaveInstanceState () callback method to completely Save the data to be restored, because the Bundle object is not designed to carry large objects (such as bitmaps) and big data, as a result, Bundle objects occupy a large amount of memory during serialization and subsequent deserialization, resulting in slow configuration changes. In this case, you can choose to retain a State object to relieve the burden of restoring the restart of the Activity.
You can retain the configuration change object during running as follows:
1. Override the onRetainNonConfigurationInstance () callback method, which returns the object to be retained.
2. When the Activity is rebuilt, call the getLastNonConfigurationInstance () method to restore the object.
When the Android system disables the Activity due to configuration changes, it calls the onRetainNonConfigurationInstance () callback method between onStop () and onDestroy. In the implementation of onRetainNonConfigurationInstance () callback, to effectively restore the status after configuration changes, it can return any desired object.
If the application needs to load data from the network, this is very valuable. If the user changes the device direction and the Activity restarts, the application must obtain data again, which will be slow. Therefore, you can implement the onRetainNonConfigurationInstance () method to let it return an object with data. Then, when the Activity is restarted, you can use the getLastNonConfigurationInstance () method to obtain the reserved object. For example:
@ Override
Public Object onRetainNonConfigurationInstance (){
Final MyDataObject data = collectMyLoadedData ();
Return data;
}
Warning do not include objects bound to the Activity, such as Drawable, Adapter, View, or other objects associated with the Context. If this is done, all View objects and resources of the original Activity instance will be leaked (resource leakage means that the application occupies these resources and thus cannot be recycled as garbage, this will lead to a large amount of memory usage ).
How to restore data when the Activity restarts:
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance ();
If (data = null ){
Data = loadMyData ();
}
...
}
In this example, the getLastNonConfigurationInstance () method returns the data saved by the onRetainNonConfigurationInstance () method. If the data object is null (this happens when the Activity restarts due to reasons other than configuration changes), the code loads the data object from the initial resource.
Handle configuration changes by yourself www.2cto.com
If the application does not need to update resources during a specific configuration change, and the restart of the Activity is required due to performance restrictions, the Activity can be declared to handle configuration changes by itself, this prevents the system from restarting the Activity.
Note: It is more difficult to use optional resources because the system cannot automatically apply the changes. This technology should be used only after the Activity is restarted (due to configuration changes), and is not recommended for large applications.
To allow the Activity to handle configuration changes, edit the corresponding <activity> element in the configuration file to include the android: configChanges attribute. This attribute value indicates the configuration to be processed. Possible values are listed in the android: configChanges attribute document ("orientation" and "keyboardHidden" are the most commonly used values. orientation is used to prevent Activity restart when the screen direction changes; keyboardHidden is used to prevent Activity restart when the keyboard availability changes ). You can declare multiple configuration values for this attribute by separating them with the pipe character "|.
For example, the following code declares an Activity that handles screen direction changes and keyboard availability changes by itself:
<Activityandroid: name = ". MyActivity"
Android: configChanges = "orientation | keyboardHidden"
Android: label = "@ string/app_name">
Through the above declaration, when one of these configurations changes, MyActivity will not restart. On the contrary, MyActivity will receive the callback of the onConfigurationChanged () method. This method is passed in a Configuration object, which specifies the new device Configuration. By reading the fields in the Configuration object, you can determine the new Configuration and make corresponding changes by updating the resources used in the interface. When this method is called, The Resources object of the Activity is updated based on the resource returned by the new configuration. Therefore, you can easily reset the UI element without restarting the Activity.
Warning: the screen size will also change when the device switches between portrait and landscape from Android3.2 (API Level 13. Therefore, when using API Level 13 or later for development, if you want to prevent the restart caused by changes in the direction at runtime, you must go to android: the configChanges property value contains "screenSize ". That is to say, android: configChanges = "orientation | screenSize" must be declared ". However, if the target platform of the application is API Level 12 or earlier, the Activity will always handle configuration changes by itself (so that the configuration changes will not restart the Activity, even running on a device of Android or later does not restart the Activity ).
For example, the onConfigurationChanged () method below checks the current device direction:
@ Override
Publicvoid 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 ();
} Elseif (newConfig. orientation = Configuration. ORIENTATION_PORTRAIT ){
Toast. makeText (this, "portrait", Toast. LENGTH_SHORT). show ();
}
}
The Configuration object represents all the current configurations, not just for the changed Configuration. Most of the time, you don't have to worry about how the configuration changes. You just need to re-allocate the available resources to the configuration being processed. For example, because Resources objects are updated, you must use the setImageResource () method to reset all ImageView objects and use appropriate Resources for new configurations.
We noticed that the value from the Configuration field is an integer, which must match the constant specified in the Configuration class. For more information about these constants, see the Configuration class description.
Remember: When you declare that you want the Activity to handle configuration changes, you must manually reset any UI elements in the Activity. If the Activity is declared to handle changes in the direction and there is an icon Change During Horizontal and vertical switchover, each resource should be reassigned during onConfigurationChanged () execution.
If you do not need to update the application based on these configuration changes, you do not need to implement the onConfigurationChanged () method. In this way, all the resources used before the configuration change will still be used after the change, simply avoiding the restart of the Activity. However, the application can be closed and restarted with the complete State. Therefore, this technology should not be considered during the survival of a common Activity, this is not only because it cannot prevent application restart caused by other configuration changes, but also because it should handle events such as getting the destroyed state before the user leaves the application and returning the application.
For more information about the Configuration changes that can be processed in the Activity, see the android: configChanges document and Configuration class.
From FireOfStar's column