One of the basic summaries: 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 = "Lifecycleactivi Ty ";p rivate context context = this;private int param = 1;//activity was called when created @Override public void onCreate (Bundle save        Dinstancestate) {super.oncreate (savedinstancestate);                LOG.I (TAG, "onCreate called.");                Setcontentview (r.layout.lifecycle);        Button btn = (button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View v) {Intent Intent = new Intent (    context, Targetactivity.class); startactivity (intent);});    //activity was called when it was created or returned back to the foreground from the background @Override protected void OnStart () {Super.onstart ();    LOG.I (TAG, "OnStart called."); }//activity back from the backgroundThe foreground is called @Override protected void Onrestart () {Super.onrestart ();    LOG.I (TAG, "Onrestart called.");    //activity is called @Override protected void Onresume () {super.onresume () when it is created or has been overwritten and returned back to the foreground from the background;    LOG.I (TAG, "Onresume called."); The//activity window Gets or loses focus when it is called, after Onresume or after OnPause/* @Override public void onwindowfocuschanged (Boolean hasfocus    ) {super.onwindowfocuschanged (hasfocus);    LOG.I (TAG, "onwindowfocuschanged called.");    }*///activity is called @Override protected void OnPause () {super.onpause () when overwritten to the following or lock screen;    LOG.I (TAG, "onPause called."); It is possible that after executing onpause or onstop, the system resource is strained to kill the activity, so it is necessary to save persistent data here}//To exit the current activity or to jump to the new activity when called @Override Prot    ected void OnStop () {super.onstop ();    LOG.I (TAG, "onStop called.");    }//is called when exiting the current activity and the activity ends after the call @Override protected void OnDestroy () {Super.ondestroy ();    LOG.I (TAG, "ondestory called.");   }/** * is called when the activity is killed by the system.  * 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.     * 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.     * Called before OnPause. */@Overrideprotected void onsaveinstancestate (Bundle outstate) {outstate.putint ("param", param); LOG.I (TAG, "onsaveinstancestate called. Put param: "+ param); super.onsaveinstancestate (outstate);} /** * 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, the system resources are strained to kill, and the user initiates the activity. * In both cases onrestoreinstancestate will be called after OnStart. */@Overrideprotected 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 have seen my Android animation frame animation This article will know that the attempt to load a frame animation in OnCreate failed because the window object is not initialized to complete, So in the end I put the loaded animation code into the onwindowfocuschanged, the problem 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:

  

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";p rivate int param = 1; @Overrideprotected void OnCreate (Bundle savedinstancestate) {sup Er.oncreate (savedinstancestate); Setcontentview (r.layout.orientation_portrait); LOG.I (TAG, "onCreate called.");} @Overrideprotected void OnStart () {Super.onstart (); LOG.I (TAG, "OnStart called.");} @Overrideprotected void Onrestart () {Super.onrestart (); LOG.I (TAG, "Onrestart called.");} @Overrideprotected void Onresume () {super.onresume (); LOG.I (TAG, "Onresume called.");} @Overrideprotected void OnPause () {super.onpause (); LOG.I (TAG, "onPause called.");} @Overrideprotected void OnStop () {super.onstop (); LOG.I (TAG, "onStop called.");} @Overrideprotected void OnDestroy () {Super.ondestroy (); LOG.I (TAG, "ondestory called.");} @Overrideprotected void Onsaveinstancestate (BunDle outstate) {outstate.putint ("param", param); LOG.I (TAG, "onsaveinstancestate called. Put param: "+ param); super.onsaveinstancestate (outstate);} @Overrideprotected 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 @overridepublic void when the direction changes Onconfigurationchanged (Configuration newconfig) {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.

One of the basic summaries: 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.