Activity life cycle

Source: Internet
Author: User

The son said: "Wen so know new, can be teacher." In the theory of language

Learning technology is also the same, for technical documents or classic technical books, expect to see the full mastery of, it is not very likely, so we need to go back and read a few times carefully to understand the essence of the author's thoughts.

Recently reviewed the life cycle of the activity, see the relevant books and official documents, but also have a great degree of improvement in the previous cognition, here to share with you.

Familiar with Java EE's friends understand the servlet technology, we want to implement a servlet, we need to inherit the corresponding base class, rewrite its methods, these methods will be called at the appropriate time by the servlet container. In fact, the activity operating mechanism in Android is similar to the servlet, the Android system is equivalent to a servlet container, activity is equivalent to a servlet, our activity in this container, all create instances, initialize , destroying instances, and so on, is called by the container, which is called the "Don t call me, I'm calling you." Mechanism.

Let's take a look at this classic life cycle flowchart:


I believe many friends have already seen this flowchart, but also basic understanding of the activity life cycle of several processes, we will say a few of these processes.

1. Start activity: The system calls the OnCreate method first, then calls the OnStart method, and finally calls Onresume,activity into the running state.

2. Current activity is overwritten or locked by other activity: the system invokes the OnPause method, pausing the execution of the current activity.

3. The current activity is returned to the foreground or unlock screen by the overwritten state: The system calls the Onresume method and enters the running state again.

4. The current activity goes to the new activity interface or press the home key to return to the main screen, itself back to the background: the system will first call the OnPause method, and then call the OnStop method, into a stagnant state.

5. The user backs back to this activity: the system calls the Onrestart method first, then calls the OnStart method, and finally calls the Onresume method, again into the running state.

6. Current activity is in a covered state or the background is not visible, that is, the 2nd and 4th steps, the system is out of memory, kill the current activity, and then the user returned to the current activity: Call OnCreate method Again, OnStart method, Onresume method To enter a running state.

7. The user exits the current activity: The system calls the OnPause method first, then calls the OnStop method, and finally calls the Ondestory method to end the current activity.

But knowing this is not enough, we have to test it ourselves to be able to understand it thoroughly.

Let's combine examples to illustrate the details of several processes in the life cycle. We create a new project called Lifecycle, which creates an activity called Lifecycleactivity, as follows:

Package com.scott.lifecycle;import android.app.activity;import android.content.context;import  android.content.Intent;import android.os.Bundle;import android.util.Log;import  Android.view.view;import android.widget.button;public class lifecycleactivity extends  Activity {        private static final  string tag =  "Lifecycleactivity";     private context context  = this;    private int param = 1;         //activity called at creation time      @Override     public  Void oncreate (bundle savedinstancestate)  {         Super.oncreate (savedinstancestate);         LOG.I (TAG,  "onCreate  called. ");      &Nbsp;          setcontentview (R.layout.lifecycle);                 button btn  =  (Button)  findviewbyid (R.ID.BTN);         Btn.setonclicklistener (New view.onclicklistener ()  {              @Override              Public void onclick (VIEW V)  {                 intent intent = new intent (context,  Targetactivity.class);                 startactivity (intent);             }         });  &Nbsp;  }        //activity is called when it is created or returned to the foreground from the background       @Override     protected void onstart ()  {         super.onstart ();         LOG.I (TAG,  " Onstart called. ");     }        //activity is called when it returns to the foreground from the background       @Override     protected void onrestart ()  {         super.onrestart ();         LOG.I (TAG,   "onrestart called.");     }        //activity is called when it is created or has been overwritten and back to the foreground in the background       @Override     protected void onresume ()  {         super.onresume ();         LOG.I (tag,  "onresume called.");     }        //activity is called when the window Gets or loses focus. After Onresume or after OnPause     /* @Override     public void  Onwindowfocuschanged (Boolean hasfocus)  {         Super.onwindowfocuschanged (Hasfocus);         LOG.I (TAG,  " Onwindowfocuschanged called. ");     }*/        //activity is called when the screen is overwritten or locked       @Override     protected void onpause ()  {         super.onpause ();         LOG.I (TAG,  "onpause called.");         //It is possible for the system resource to kill the activity after executing onpause or onstop, so it is necessary to save persistent data here      }     &nbsp  //is called when exiting the current activity or jumping to a new activity      @Override      Protected void onstop ()  {        super.onstop ();         LOG.I (tag,  "onstop called.");         }        // Called when exiting the current activity, the activity ends after the call      @Override     protected void  ondestroy ()  {        super.ondestroy ();         LOG.I (tag,  "ondestory called.");     }        /**     *  activity is called when the system is killed .     *  for example: when the screen orientation changes, the activity is destroyed and rebuilt; The current activity is in the background, system resources are strained to kill .     *  in addition, this method is also called when jumping to other activity or pressing the home key to return to the main screen, in order to save the state of the current view component. & nbsp;    *  is called before OnPause.      */    @ Override    protected void onsaveinstancestate (Bundle outState)  {         outstate.putint ("param",  param);         LOG.I (tag,  "onsaveinstancestate called. put param: "  +  param);         super.onsaveinstancestate (outState);     }        /**     *  The activity is called when the system is killed and then rebuilt .     *  for example: when the screen orientation changes, the activity is destroyed and rebuilt; The current activity is in the background and the system resources are strained to kill it. , the user also starts the activity.     *  in both cases onrestoreinstancestate will be called, after OnStart .      */     @Override     protected void  Onrestoreinstancestate (bundle savedinsTancestate)  {        param = savedinstancestate.getint ( "Param");         LOG.I (tag,  "onrestoreinstancestate called.  get param:  " + param);         Super.onrestoreinstancestate (savedinstancestate);     }}

It is noted that in addition to a few common methods, we have added onwindowfocuschanged, Onsaveinstancestate, and Onrestoreinstancestate methods:

1.onWindowFocusChanged method: Called when the activity window Gets or loses focus, such as when it was first presented to the user at the time of creation, and the current activity is overwritten by other activity The current activity goes to another activity or presses the home key back to the main screen, and the user exits the current activity. In these cases, onwindowfocuschanged is called, and when the activity is created it is called after Onresume, when the activity is overwritten or retired or the current activity exits, It is called after OnPause:


This method is useful in some situations, for example, when the program starts to get the size of a particular view component, it may not be available in OnCreate because the Window object is not created yet, and we need to get it in onwindowfocuschanged. If you've already seen my Android animation frame animation This article will know that the reason why the attempt to load a frame animation in OnCreate was unsuccessful because the window object was not initialized, so I finally put the code that loaded the animation In the onwindowfocuschanged, the problem was solved. But you might be wondering why I commented it out in the code, because I have its execution log for each operation of the current activity, and I'm afraid it's going to affect the clarity of the whole process, so put it off, and you just have to know where it's going to be and how it's done.

2.onSaveInstanceState: (1) After the activity is covered or back to the background, the system resources are not enough to kill, this method will be called, (2) when the user changes the screen orientation, this method will be called; (3) This method is called when the current activity jumps to another activity or presses the home key to return to the main screen. In the first case, we cannot guarantee when the system will be dispatched according to the degree of resource stress; the second is the screen flipping direction, the system first destroys the current activity, and then rebuilds a new one, we can save some temporary data when we call this method. In the third case, the system calls this method to save the state of each view component in the current window. The order in which the onsaveinstancestate is called precedes OnPause.

3.onRestoreInstanceState: (1) After the activity is covered or back to the background, the system resources are not enough to kill it, and then the user returned to the activity, this method will be called, (2) in the process of the user changing the screen direction, the reconstruction, This method is called. We can override this method so that some temporary data can be recovered. The order in which the onrestoreinstancestate is called is after OnStart.

After highlighting the three relatively unfamiliar methods, let's take a look at the activity and see what the process is like in the life cycle:

1. Start activity:


After the system calls OnCreate and OnStart, the Onresume is called, and since then the activity has entered a running state.

2. Jump to another activity, or press the home button to return to the main screen:


We see that at this point the Onsaveinstancestate method is called before OnPause, and notice that OnStop is called after OnPause back to the background.

3. Back to front desk from backstage:


When going from the backstage to the foreground, the system calls the Onrestart method, then calls the OnStart method, and finally calls the Onresume method, and the activity goes into the running state.

4. Modify the configuration of targetactivity in Androidmanifest.xml, set the Android:theme property to @android: style/ Theme.dialog, and then click the button in the lifecycleactivity, the jump behavior becomes targetactivity overlay to the lifecycleactivity, at this time the method is called:


Note there is another situation is that we click on the button, just press the lock screen button, the effect is the same as above.

We notice that at this point the OnPause method of the lifecycleactivity is called, and the OnStop method is not called, because at this time the lifecycleactivity is not relegated to the background, just being overwritten or locked screen The onsaveinstancestate will be called before OnPause.

5. Press the fallback key to make the lifecycleactivity from being overwritten back to the front, or press unlock key to unlock the screen:


At this point only the Onresume method is called and goes directly to the running state again.

6. Exit:


The last Ondestory method is called, marking the end of lifecycleactivity.

Everyone seems to notice that, in all the process, there is no onrestoreinstancestate, this is not surprising, as we have said before, Onrestoreinstancestate is called when the user returns to the activity after killing an activity that is not in the foreground, or when the user changes the screen orientation of the two rebuilds. It is difficult for us to demonstrate the first case, and we can demonstrate the process in the context of the second case. By the way also explain to you the screen direction of the change of coping strategies.

Let's start with a little bit of knowledge about the orientation of the activity screen.

We can specify a specific direction for an activity, and the direction of the display will not change even after the screen orientation is rotated:

1. Specify as vertical screen: Set android:screenorientation= "Portrait" in Androidmanifest.xml for the specified activity, or specify in the OnCreate method:

Setrequestedorientation (activityinfo.screen_orientation_portrait); Vertical screen

2. Specify as a horizontal screen: set android:screenorientation= "Landscape" in Androidmanifest.xml for the specified activity, or specify in the OnCreate method:

Setrequestedorientation (Activityinfo.screen_orientation_landscape); Horizontal screen

Setting specific directions for activity in your application is a common approach that can save us a lot of unnecessary hassle. However, today we are talking about the life cycle when the screen orientation changes, so we do not use the fixed screen orientation approach.

Let's take a look at the life cycle of screen transitions with examples, and we'll create a new activity named Orientationactivity, as follows:

package com.scott.lifecycle;import android.app.activity;import  Android.content.res.configuration;import android.os.bundle;import android.util.log;public class  OrientationActivity extends Activity {         private static final string tag =  "Orientationactivity";     private int param = 1;         @Override      protected void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);         setcontentview (r.layout.orientation_portrait);         LOG.I (TAG,   "oncreate called.");     }         @Override      Protected void onsTart ()  {        super.onstart ();         LOG.I (tag,  "onstart called.");     }         @Override      Protected void onrestart ()  {        super.onrestart ();         LOG.I (tag,  "onrestart called.");     }         @Override      Protected void onresume ()  {        super.onresume ();         LOG.I (tag,  "onresume called.");     }         @Override      Protected void onpause ()  {        super.onpause ();          LOG.I (tag,  "onpause called.");     }         @Override      Protected void onstop ()  {        super.onstop ();         LOG.I (tag,  "onstop called.");     }         @Override      Protected void ondestroy ()  {        super.ondestroy ();         LOG.I (tag,  "ondestory called.");     }     @Override     protected void  Onsaveinstancestate (bundle outstate)  {         Outstate.putint ("param",  param);         LOG.I (TAG,  " Onsaveinstancestate called. put param:  " + param);         Super.onsaveinstancestate (outstate);     }        @ Override    protected void onrestoreinstancestate (Bundle savedInstanceState )  {        param = savedinstancestate.getint ("param");         LOG.I (tag,  "Onrestoreinstancestate called. get  param:  " + param);         Super.onrestoreinstancestate (savedinstancestate);    }         //when android:configchanges= "orientation" is specified, onconfigurationchanged is called when the direction changes     @ Override    public void onconfigurationchanged (Configuration newConfig)  {      &Nbsp; super.onconfigurationchanged (Newconfig);         LOG.I (TAG,   "onconfigurationchanged called.");         switch  (newconfig.orientation)  {         case Configuration.ORIENTATION_PORTRAIT:             setcontentview (r.layout.orientation_portrait);             break;         case configuration.orientation_landscape:             setcontentview (R.layout.orientation_landscape);             break;        }    }}

First we need to go into "settings->display", "auto-rotate screen" a selection, indicating that we can automatically rotate the screens according to direction, then we can test the process, when we rotate the screen, We found that the system will destroy the current activity first and then rebuild a new one:


The system first calls the Onsaveinstancestate method, we save a temporary parameter inside the bundle object, and then we successfully remove the parameter after the activity is rebuilt.

To avoid this process of destroying the rebuild, we need to orientationactivity the corresponding <activity> configuration in Androidmainfest.xml android:configchanges= " Orientation ", and then we test it again, I tried to do the rotation four times, print the following:


As you can see, only the Onconfigurationchanged method is called at each rotation direction, and there is no process to destroy the rebuild.

Here are a few things to keep in mind:

1. If the <activity> is configured with the Android:screenorientation attribute, the android:configchanges= "orientation" will be invalidated.

2. The simulator differs greatly from the real machine: If you do not configure the Android:configchanges property or the configuration value to orientation in the simulator, cut to the horizontal screen to perform a destruction--rebuild, cut to the vertical screen to perform two times. The real machine is one time. If the emulator is configured with android:configchanges= "Orientation|keyboardhidden" (if Android4.0, it is "orientation|keyboardhidden| ScreenSize "), cut the vertical screen to perform a onconfigurationchanged, cut the horizontal screen to perform two times. The real machine is one time.

Activity life cycle and the robustness of the program is closely related to the hope that friends can seriously understand, skilled application.


Activity life cycle

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.