Android Component Family-----activity Save Status

Source: Internet
Author: User

This essay will explain in detail the concept of activity preservation, that is, saving activity state.

I. Activity status Maintenance concept

It is important to keep the activity state, for example, when we play a game, suddenly a phone call, this time after we answer the phone we return to the game, this time we want the game or the previous progress, or an unexpected event, the game this application was closed, If we re-open the game at this time, if we still want to go back to the previous progress, we need to save its state, so that when the activity is destroyed, we can also return to the previous progress according to the saved state. This is the state of activity preservation.

In two ways, the state of the activity will be saved.

The status of the activity is saved in two ways, and we first look at both of these ways through the diagram provided by the official Android document:

1. When an activity is in front of another activity, that is, another activity is in the stop state, this activity still occupies the memory, and maintains the activity state, if you click the Back button at this time, Then the first activity will return to the foreground interface, when the activity will remain in its original state, and we do not need to regain its state.

2. When our activity is in a stop state in the background, if there is a higher priority activity to obtain resources at this time, the system may break activity in the stop state, reclaim its memory, At this point the activity object will be destroyed, if we must call a Onsaveinstancestate () method to hold the object state of our activity.

Onsaveinstancestate (Bundle Outstate) This method accepts a bundle type parameter, and we can save the state we need to save through the bundle's putstring, Putint method.

When our activity is very easily destroyed, the system calls the Onsaveinstancestate () method, and if the system kills the activity thread, the activity object is destroy, When this activity is opened again, the activity is recreated, and this time the Bundle object in the Onsaveinstancestate method is passed to the activity's onCreate () and Onrestoreinstancestate () method,

Using either of these two methods, we can restore the previous state of our activity based on the previously saved Bundle object.

Iii. Methods of Onsaveinstancestate

protected void Onsaveinstancestate (Bundle outstate)

Let's take a closer look at this method, which allows us to restore the saved state of an activity when it is killed and in the future if it is to be recreated. We don't have to wonder. This method and the invocation period of the activity lifecycle function method, such as the OnPause () method, are invoked when an activity is in the background or is vulnerable to corruption.

There are two cases where this onsaveinstancestate method is not called:

①activity B is in front of activity A, if you click the Back button, activity B will call the OnPause, OnStop method, at which time the system does not call the Onsaveinstancestate () method, because this is the time we display Activity B is shown, so the system thinks that calling Onsaveinstancestate () is not and wants.

②activity B is in front of activity a, when activity A is in the background state, but still consumes memory resources, and when the back button is passed, activity a returns to the foreground, onsaveinstancestate () The method is also unnecessary to call, because activity a itself is now fully saved in the current state.

Next we take a look at the invocation of activity's onsaveinstancestate (), OnCreate (), and Onrestoreinstancestate () methods to keep our activity alive.

public class Thirdactivity extends activity{private final String TAG = "thirdactivity";    Private button button;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.third);                LOG.I (TAG, "thirdactivity onCreate");            if (savedinstancestate! = null) {String name = (string) savedinstancestate.getstring ("name");        Toast.maketext (thirdactivity.this, "onCreate--->" + Name, 1). Show ();        } button = (button) Findviewbyid (R.id.button);            Button.setonclicklistener (New Onclicklistener () {@Override public void OnClick (view view)                {Intent Intent = new Intent ();                Intent.setclass (Thirdactivity.this, Fourthactivity.class);            StartActivity (Intent);            }        }); } @Override protected void OnStart () {Super.onstarT ();    LOG.I (TAG, "thirdactivity OnStart");        } @Override protected void Onresume () {super.onresume ();    LOG.I (TAG, "thirdactivity onresume");        } @Override protected void OnPause () {super.onpause ();    LOG.I (TAG, "thirdactivity onPause");         } @Override protected void Onsaveinstancestate (Bundle outstate) {super.onsaveinstancestate (outstate);        LOG.I (TAG, "thirdactivity onsaveinstancestate");    Outstate.putstring ("name", "Xiaoluo"); } @Override protected void Onrestoreinstancestate (Bundle savedinstancestate) {super.onrestoreinstance        State (Savedinstancestate);        LOG.I (TAG, "thirdactivity onrestoreinstancestate");            if (savedinstancestate! = null) {String name = (string) savedinstancestate.getstring ("name");        Toast.maketext (thirdactivity.this, "onrestoreinstancestate--->" + Name, 1). Show (); }} @Override protected VoID onStop () {super.onstop ();    LOG.I (TAG, "thirdactivity onStop");        } @Override protected void Onrestart () {Super.onrestart ();    LOG.I (TAG, "thirdactivity Onrestart");        } @Override protected void OnDestroy () {Super.ondestroy ();    LOG.I (TAG, "thirdactivity OnDestroy"); }}

We see that in this activity we have implemented its onsaveinstancestate (), OnCreate () and Onrestoreinstancestate () methods, which we have in onsaveinstancestate () method to save the state of the current activity:

    @Override    protected void onsaveinstancestate (Bundle outstate)    {        super.onsaveinstancestate (outstate);        LOG.I (TAG, "thirdactivity onsaveinstancestate");        Outstate.putstring ("name", "Xiaoluo");    }    

Then try to get the saved bundle object in the OnCreate () method and the Onrestoreinstancestate () method, when the activity is first created, onCreate () and the bundle object in the Onrestoreinstancestate () method is null.

protected void OnCreate (Bundle savedinstancestate)    {        super.oncreate (savedinstancestate);        Setcontentview (R.layout.third);        LOG.I (TAG, "thirdactivity onCreate");                if (savedinstancestate! = null)        {            String name = (string) savedinstancestate.getstring ("name");            Toast.maketext (thirdactivity.this, "OnCreate--->  " + Name, 1). Show ();                Button = (button) Findviewbyid (R.id.button);        Button.setonclicklistener (New Onclicklistener ()        {            @Override public            void OnClick (view view)            {                Intent Intent = new Intent ();                Intent.setclass (Thirdactivity.this, fourthactivity.class);                StartActivity (intent);}}        );            }
@Override    protected void onrestoreinstancestate (Bundle savedinstancestate)    {        Super.onrestoreinstancestate (savedinstancestate);        LOG.I (TAG, "thirdactivity onrestoreinstancestate");        if (savedinstancestate! = null)        {            String name = (string) savedinstancestate.getstring ("name");            Toast.maketext (thirdactivity.this, "onrestoreinstancestate--->" + Name, 1). Show ();        }    }

In both of these methods, we use the Toast popup to see if we can print out the status values saved by the bundle. In order to simulate this experiment, we need to switch the screen of the phone.

When the orientation of the screen is changed, the system will first destroy and then recreate the activity object to reload the interface according to our configured resource file, which is very important to preserve the state of our activity, because in most cases The change in the screen is always happening, so we have to use the Onsaveinstancestate () method to preserve the state of our activity.

Let's take a look at the experimental results:

We see that when we invert the screen, because we have previously saved the state of the activity through the Onsaveinstancestate () method, when the activity is from destroy to recreate, The saved bundle objects are passed to the OnCreate and Onrestoreinstancestate methods, and we are able to restore the state of our activity.

Iv. onsaveinstancestate () method for Android View Control

When we create an activity object, if we do not rewrite the parent class's Onsaveinstancestate () method, some of our activity states will also be called by the parent class activity's default Onsaveinstancestate () method to save it. In particular: the Onsaveinstancestate () method of the parent class invokes the corresponding Onsaveinstancestate () method of each View object in the layout file to maintain its state. Most widget controls on Android are very good implementations of the Onsaveinstancestate () method, so our changes to the values of these spaces will be automatically saved. For example, our edittext, CheckBox control, when we enter our values only, when the activity is destroy-->recreate, at this time our values will still be preserved, if : If we need to save the state of a view control, we have to give it a unique identifier (specified by the Android:id property), and if we do not specify it, the system will not save its state . For example, let's take a look at the following example:

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "> <textview A Ndroid:id= "@+id/textview1" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" a Ndroid:textsize= "20SP" android:text= "Usenrame"/> <edittext android:id= "@+id/username" a Ndroid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:layout_torightof= "@id/TEXTVI Ew1 "android:inputtype=" text "/> <textview android:id=" @+id/textview2 "Android:layout_wi Dth= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@id/username" android:t Extsize= "20SP" android:text= "email"/> <edittext android:layout_width= "Match_parent" and roid:layout_height= "Wrap_content"        android:layout_below= "@id/username" android:layout_torightof= "@id/textview2" android:inputtype= "text        EmailAddress "/> <checkbox android:id=" @+id/checkbox1 "android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_margintop= "100DP" android:text= "basketball"/> <C Heckbox android:id= "@+id/checkbox2" android:layout_width= "wrap_content" android:layout_height= "Wrap_ Content "android:layout_torightof=" @id/checkbox1 "android:layout_aligntop=" @id/checkbox1 "Android:tex        t= "Soccer"/> <checkbox android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_torightof= "@id/checkbox2" android:layout_aligntop= "@id/checkbox1" android:text= "Tennis"/>< /relativelayout>

Our activity interface has a total of 5 view controls, where username this edittext we specify Id,email this edittext does not have a specified ID, and the following three checkboxes, Only the last checkbox does not specify an ID for it, so let's see if it will save the state of each view control when the activity is recreated:

We entered the values in the two text boxes and checked the three checkboxes, and we flipped our screen:

We see that because username this edittext and the first two checkboxes we have given it an ID, the system calls its Onsaveinstancestate () method to save our view control state. For email this edittext and last checkbox, we did not specify an ID identifier, so the system does not automatically save the state for it.

Note: Although the default activity's Onsaveinstancestate () method will save the state of our view control, we still recommend re-onsaveinstancestate () method to save the state of some of our extra activity, and when we rewrite the OnCreate (), Onsaveinstancestate (), and Onrestoreinstancestate () methods separately, we first call the parent class's method. This will save the state of our view control by default.

Finally, we conclude by saying that because the Onsaveinstancestate () method is not guaranteed to be called, we can only use the Onsaveinstancestate () method to hold the temporary state information of our activity. For objects or States to persist, we should do so in the OnPause () method .

Android Component Family-----activity Save Status

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.