Android Basics Summary: (iv) Activity (instancestate)

Source: Internet
Author: User
Tags unique id

This article describes two mysterious methods of activity in Android: Onsaveinstancestate () and Onrestoreinstancestate (), and after introducing these two methods, And then separately to achieve the use of instancestate to save and restore data features, Android implementation of screen rotation asynchronous download effect such as two examples.

First, introduce Onsaveinstancestate () and Onrestoreinstancestate (). With regard to these two methods, some friends may be seldom used in the Android development process, but sometimes mastering their usage will help us to get better results. This is especially true when an application exits without knowing how to implement its data saving capabilities. Let's take a look at how these two methods work.


1. Basic Role
Activity's Onsaveinstancestate () and onrestoreinstancestate () are not life cycle methods, they are not necessarily triggered, unlike life cycle methods such as OnCreate (), OnPause (). Onsaveinstancestate () is called when an activity is destroyed by the system when an application encounters an unexpected condition (such as insufficient memory, the user presses the home key directly). However, when the user actively destroys an activity, such as pressing the return key in the app, Onsaveinstancestate () is not called. Because in this case, the behavior of the user determines that there is no need to save the activity State. usually Onsaveinstancestate () is only suitable for storing some temporary state, while OnPause () is suitable for persisting data.
The state of each instance is saved before the activity is killed to ensure that the state can be in OnCreate (bundle) or Onrestoreinstancestate (bundle) ( The incoming bundle parameters are recovered from the Onsaveinstancestate package. This method is called before an activity is killed and can revert to its previous state when the activity returns at some point in the future.
For example, if activity B is enabled and is located at activity A's front end, at some point, activity a because the system reclaims the resources of the problem to be killed, a through onsaveinstancestate will have the opportunity to save their user interface state, Enables future users to return to activity a by OnCreate (bundle) or onrestoreinstancestate (bundle) to restore the state of the interface.
About Onsaveinstancestate () is to save some view useful data to a Parcelable object and return it inside the function. Calls the view's Onsaveinstancestate () in the Onsaveinstancestate (Bundle outstate) of the activity, returns the Parcelable object,
The bundle's Putparcelable method is then used to store the bundle Savedinstancestate.
When the system calls the activity's onrestoreinstancestate (bundle savedinstancestate), the Getparcelable method of the same bundle gets the Parcelable object, The Parcelable object is then passed to the view's Onrestoreinstancestate (parcelable state). Read the saved data from the parcelable in the view's onrestoreinstancestate for view use.

This is the basic function and usage of the two functions of onsaveinstancestate () and Onrestoreinstancestate ().


2. Onsaveinstancestate () when to call
First look at application fundamentals on a passage:
Android calls Onsaveinstancestate () before the activitybecomes vulnerable to being destroyed by the system, but does not B Othercalling it when the instance are actually being destroyed by a user action (Suchas pressing the back key).
As you can tell, when an activity becomes "easy" to be destroyed by the system, the activity's onsaveinstancestate () is executed unless the activity is actively destroyed by the user, such as when the user presses the back key.
Notice the double quotes above, what is "easy"? It means that the activity has not been destroyed, but only a possibility. What are the possibilities? By overriding the OnXxx method of all life cycles of an activity, including the Onsaveinstancestate () and Onrestoreinstancestate () methods, We can clearly see when an activity (assuming activity a) is displayed at the top of the current task, when its onsaveinstancestate () method is executed, in several cases:
(1), when the user presses the home button.
It is obvious that the system does not know how many other programs to run after you press home, and it is not known whether activity A will be destroyed, so the system will call Onsaveinstancestate (), giving the user the opportunity to save some non-permanent data. The following are some of the conditions in which the analysis follows this principle
(2), long press the home key, choose to run other programs.
(3), Press the power button (turn off the screen display).
(4), when starting a new activity from activity a.
(5), the screen direction when switching, such as from the vertical screen when switching to a horizontal screen.
Before the screen is switched on, activity A is destroyed, and activity A is automatically created after the screen switch, so onsaveinstancestate () is bound to be executed and will certainly execute onrestoreinstancestate ().

All in all, the invocation of Onsaveinstancestate () follows an important principle that onsaveinstancestate () will be called by the system when there is a possibility of destroying our activity "without your permission", which is the responsibility of the system, Because it has to provide an opportunity for you to save your data (of course you don't save it then just do it yourself). If called, the call occurs before the OnPause () or OnStop () method. (although most of the tests were found before OnPause ())


3. Onrestoreinstancestate () when to call
onrestoreinstancestate () is invoked on the premise that activity a "does" have been destroyed by the system, and that the method will not be invoked if it is merely stuck in the case where activity A is being displayed, for example, The user presses the home key back to the main interface, and then the user then returns to activity a, in which event A is not normally destroyed by the system for memory reasons, so activity A's Onrestoreinstancestate method is not executed This also shows that the two, in most cases, are not paired to be used.

Onrestoreinstancestate () is called between OnStart () and Onpostcreate (Bundle).


4. Default implementation of the Onsaveinstancestate () method
If we do not overwrite the Onsaveinstancestate () method, the default implementation of this method automatically saves some state data in the activity, such as the state of the various UI controls in the activity: Almost all UI controls defined in the Android application framework implement the Onsaveinstancestate () method appropriately, so these UI controls automatically save and restore state data when activity is destroyed and rebuilt. For example, the EditText control automatically saves and restores the input data, and the CheckBox control automatically saves and restores the selected state. Developers only need to specify a unique ID for these controls (by setting the Android:id property), The rest can be done automatically. If no ID is specified for the control, the control does not perform automatic data saving and recovery operations.

As mentioned above, if we need to overwrite the Onsaveinstancestate () method, the default implementation of the method is typically called in the first line of code: Super.onsaveinstancestate (outstate).


5. Whether you need to override the Onsaveinstancestate () method
Since the default implementation of the method can automatically save the UI control's state data, when do you need to overwrite the method?
If you need to save additional data, you need to overwrite the Onsaveinstancestate () method. It is important to note that the Onsaveinstancestate () method is only suitable for storing transient data, such as the state of the UI control, the value of the member variable, and not the persisted data, which should be persisted when the user leaves the current activity at OnPause () (for example, saving data to a database or file). In this case, it is important to understand that it is not suitable for storing more time-consuming data in OnPause ().

Because the Onsaveinstancestate () method method is not necessarily called, it is not appropriate to persist persisted data in the method, such as inserting records into the database, and so on. The operation to save persisted data should be placed in OnPause (). If it is a permanent value, it is saved in OnPause (), and if it is large, another thread, do not block the UI thread.


6. Other circumstances that trigger activity destruction and reconstruction
In addition to the fact that the system is out of memory to destroy activity, changes in some system settings can cause activity to be destroyed and rebuilt. For example, change the screen orientation (see the example above), Change device language settings, keyboard popup, etc.

Additionally, when the orientation of the screen changes, the activity is destroyed and recreated, if you want to cache some data before the activity is destroyed, and restore the cached data after the activity is recreated. You can rewrite the activity's onsaveinstancestate () and Onrestoreinstancestate () methods, as shown in the following code:

<span style= "FONT-SIZE:18PX;" >import Android. R;import Android.app.activity;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import android.widget.toast;/** * Android uses instancestate to save and restore data */public class Mainactivity extends Activity {private String Message = "";p rivate EditText Text = null;private Button button = null;/** Called when the activity is first created. */@Overridepublic void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main); text = (EditText) Findviewbyid (r.id.edittext1); button = (button) Findviewbyid (R.id.btnsave); Button.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {Toast.maketext ( Getapplicationcontext (), "Save", Toast.length_short). Show ();}}); @Overridepublic void Onresume () {super.onresume (); Toast.maketext (Getapplicationcontext (), message, Toast.length_long). Show (); @Overridepublic VOID onsaveinstancestate (Bundle savedinstancestate) {super.onsaveinstancestate (savedinstancestate); Savedinstancestate.putstring ("Message", Text.gettext (). toString ());} @Overridepublic void Onrestoreinstancestate (Bundle savedinstancestate) {super.onrestoreinstancestate ( savedinstancestate); message = savedinstancestate.getstring ("message");}} </span>
It is also important to note that the Onsaveinstancestate () method is not necessarily called, because some scenarios do not need to save state data. For example, when the user presses the back key to exit the activity, the user obviously wants to close the activity, at which point there is no need to save the data for the next recovery, i.e. the Onsaveinstancestate () method will not be called. If the Onsaveinstancestate () method is called, the call occurs before the OnPause () or OnStop () method.
The code looks like this:

<span style= "FONT-SIZE:18PX;" > @Overridepublic void onsaveinstancestate (Bundle savedinstancestate) {Savedinstancestate.putboolean ("Myboolean" , true); Savedinstancestate.putdouble ("MyDouble", 1.9); Super.onsaveinstancestate (savedinstancestate);} </span>
<span style= "FONT-SIZE:18PX;" > @Overridepublic void onrestoreinstancestate (Bundle savedinstancestate) {super.onrestoreinstancestate ( Savedinstancestate); Boolean Myboolean = Savedinstancestate.getboolean ("Myboolean");d ouble MyDouble = Savedinstancestate.getdouble ("MyDouble");} </span>
we can use the rotating screen to test our program's ability to save state. Because the activity is re-executed OnCreate (), OnStart () and so on, it is important for the program to be able to save the state at this time because of the general rotation. Consider using this method to save data. Of course, we can use Onretainnonconfigurationinstance () and Getlastnonconfigurationinstance (onsaveinstancestate) When rotating the screen, These two methods are used to save the state of the toggle screen. Unlike Onsaveinstancestate (), Onretainnonconfigurationinstance () and Getlastnonconfigurationinstance () method is primarily used to save data when rotating between screens.
As shown in the following code:
<span style= "FONT-SIZE:18PX;" > @Overridepublic Object Onretainnonconfigurationinstance () {//here to set what needs to be saved, not bundles when switching, we can replace it with object directly. Returnsuper.onretainnonconfigurationinstance ();} </span>
You can restore the screen without using onrestoreinstancestate () instead of using getlastnonconfigurationinstance (). We can get the last saved object directly in the OnCreate () method.
<span style= "FONT-SIZE:18PX;" > @Overrideprotectedvoid onCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); Setcontentview (r.layout.main);//Gets the object that was saved last time the screen was toggled object obj = Getlastnonconfigurationinstance ();} </span>

For our program, more or less we need to jump between the activity, some of which are to obtain resources in the system or some necessary information, and generally by starting activity (common startactivity () and the Startactivityforresult () function) to operate. During this jump, our current activity temporarily loses focus, is in a non-operational state, can be preceded by the Onsaveinstancestate () method to save some temporary data. When returning to the previous activity, the previous activity re-acquires the focus, and the system triggers the Onrestoreinstancestate () method to get some data before the focus is lost. The Onretainnonconfigurationinstance () method also has a similar function to handle such data operations. As previously stated, the Onretainnonconfigurationinstance () method is primarily used for the rotation of the screen.
Speaking of this, there may be people to ask, since Onsaveinstancestate () and onretainnonconfigurationinstance () can achieve the function of saving data, if it is two simultaneous use, the order of execution which precedes, Which one is behind it? According to the official Android website, if two methods appear at the same time, the Onsaveinstancestate () method executes earlier, while the Onretainnonconfigurationinstance () method executes at the back. Their order of execution is between OnStop () and OnDestroy (), which we all need to be aware of.
Previously seen on other sites, some friends said: "Onsaveinstancestate () and onretainnonconfigurationinstance () since all can achieve the function of saving data, and onsaveinstancestate ( Compared to the Onretainnonconfigurationinstance () method can achieve more cases of data preservation function, then onretainnonconfigurationinstance () is not redundant? "。 In this regard, onretainnonconfigurationinstance () is not a redundant function from a design standpoint. In general, if the data we want to save is not very large and is suitable for the bundle, then using Onsaveinstancestate () is more appropriate. If the data to be saved is not suitable for the bundle (e.g. a socket) or if the data is large (e.g. a bitmap), then we should use Onretainnonconfigurationinstance () at this time, And we use Onretainnonconfigurationinstance () to save any type of object, like Asynctask and Sqlitedatabse, which we can save. These types of data may be reused by a new activity instance. So Onsaveinstancestate () and onretainnonconfigurationinstance () play different roles in our program and need to be lowered at different times to handle different types of data.
For example, the following code shows that you want to save a complex data:

Import Android.graphics.bitmap;public class Dataholder {int A; Bitmap b; String s;public Object onretainnonconfigurationinstance () {dataholder DH = new Dataholder ();d h.a = a;dh.b = B;DH.S = S;ret Urn dh;}}

However, Onretainnonconfigurationinstance () is an obsolete method in the new version of the SDK, and we can use Setretaininstance (Boolean) Instead of onretainnonconfigurationinstance (), we can still use onretainnonconfigurationinstance () in the old platform. If some of your friends don't know how to use Setretaininstance (Boolean) to save your custom object data, you can use Onretaincustomnonconfigurationinstance () to represent Onretainnonconfigurationinstance (), while using getlastcustomnonconfigurationinstance () Instead of Getlastnonconfigurationinstance ().

here is an effect of using onretainnonconfigurationinstance () and getlastnonconfigurationinstance () to asynchronously download the update progress bar and save the data when the screen rotates. The code looks like this:
<span style= "FONT-SIZE:18PX;" >import android.app.activity;import android.os.asynctask;import Android.os.bundle;import android.os.SystemClock ; Import Android.util.log;import android.view.view;import android.widget.progressbar;/** * Android for screen rotation asynchronous Download effect * * @ Description:android implementation of screen rotation asynchronous download Effect * * @File: Rotationasyncactivity.java * * @Package com.rotation.demo * * @Author Hanyo Nglu * * @Date 2012-03-28 PM 08:14:57 * * @Version V1.0 */public class Rotationasyncactivity extends Activity {//progress bar PRIV Ate ProgressBar ProgressBar = null;//Asynchronous Task class private rotationasynctask asynctask = null; @Overridepublic void OnCreate (Bundl E savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.main);p Rogressbar = (progressBar ) Findviewbyid (r.id.progress);//Get Object Asynctask = (rotationasynctask) getlastnonconfigurationinstance (); if (asyncTask = = null) {Asynctask = new Rotationasynctask (this), Asynctask.execute ();} else {Asynctask.attach (this); UpdateProgress ( Asynctask.getprogress ()); IF (asynctask.getprogress () >=) {Markasdone ();}}} /** * Save Object */@Overridepublic Object Onretainnonconfigurationinstance () {Asynctask.detach (); return asynctask;} private void UpdateProgress (int progress) {progressbar.setprogress (progress);} private void Markasdone () {Findviewbyid (r.id.completed). setvisibility (view.visible);} Asynchronous task class private static class Rotationasynctask extends Asynctask<void, Void, void> {private rotationasyncactivity a ctivity = null;private int progress = 0;/** * default constructor */public Rotationasynctask () {//TODO auto-generated constructor stub }/** * with Parametric constructor * * @param activity */public rotationasynctask (rotationasyncactivity activity) {Attach (activity); @Overrideprotected void Doinbackground (void ... unused) {for (int i = 0; i <; i++) {systemclock.sleep ($);p Ublishpro Gress ();} return null;} @Overrideprotected void onprogressupdate (void ... unused) {if (activity = = null) {LOG.W ("rotationasyncactivity", " Onprogressupdate () ");} else {progress + = 5;activity.updateproGress (progress);}} @Overrideprotected void OnPostExecute (void unused) {if (activity = = null) {LOG.W ("rotationasyncactivity", " OnPostExecute () ");} else {activity.markasdone ();}} protected void Detach () {activity = null;} protected void Attach (rotationasyncactivity activity) {this.activity = activity;} protected int getprogress () {return progress;}}} </span>
When we run the example, we will find that no matter how the screen is rotated will not affect the progress bar update and download, need to explain that I did not set up the download function, interested or need to add the friends themselves. The implementation is as follows:

The above is the process of saving data and recovering data in Android on Instancestate, here I would like to repeat: Onsaveinstancestate () and onrestoreinstancestate () mechanism to save the data, It saves and recovers data only when non-user explicit instructions kill the application. We can use it in our program to save data, as a way to save data, but in the use of the process needs to pay attention to its use of principles and methods.


Android Basics Summary: (iv) Activity (instancestate)

Related Article

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.