Basic summary between articles: Activity life cycle

Source: Internet
Author: User

Confucius: The new is known by Wen. It can serve as a teacher. Analects

The same learning skills. For the technical documents or books of the classic technology, look forward to see it fully mastered, which is basically impossible, so we often come back several times, and then carefully study, in order to understand the essence of the author's thoughts.

Recently, he thought about the activity life cycle and took a look at related books and official documents. Also have a small harvest. There has been a great improvement in the perception of the past, and here we 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. Override its methods, which are called by the servlet container at the appropriate time. In fact, the activity execution mechanism in Android is somewhat similar to the servlet. The Android system is equivalent to a servlet container. Activity is equivalent to a servlet. Our activity is in this container, everything that creates instances, initializes, destroys 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. We also have a basic understanding of several processes in the activity life cycle, and we will talk about these processes.

1. Start activity: The system will call the OnCreate method first. Then call the OnStart method, and finally call onresume,activity to enter execution state.

2. Current activity is covered by other activity or locked screen: The system calls the OnPause method, pausing the current activity's operation.

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 execution state again.

4. Current activity go to the new activity interface or press the home key to return to the main screen. itself back in the background: The system calls the OnPause method first. The OnStop method is then called to enter a stagnant state.

5. The user backs back to this activity: the system calls the Onrestart method first and then calls the OnStart method. Finally, call the Onresume method and enter the execution state again.

6. The current activity is in a covered state or the background is not visible, that is, steps 2nd and 4th. system memory is low. Kill the current activity, and then the user returns to the current activity: Call the OnCreate method again, OnStart method, Onresume method, into the execution state.

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

But know that these are not enough, we must personally test the ability of profound experience, mastery.

Let's combine the examples below. To demonstrate the specifics of several processes in the life cycle. We created a new project called Lifecycle. Create an activity named Lifecycleactivity, such as the following:

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 to the foreground from the background @Override protected void OnStart () {Super.onstart ();    LOG.I (TAG, "OnStart called."); }//activity from backstage againCalled when returning to the foreground @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 to the foreground from the background;    LOG.I (TAG, "Onresume called."); The//activity form is called when it 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 overwritten to the following or lock screen when called @Override protected void OnPause () {super.onpause ();    LOG.I (TAG, "onPause called."); It is possible that after running OnPause or OnStop, the system resource is strained to kill the activity, so it is necessary to save persistent data here}//exit the current activity or 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 button 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, 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 also joined the onwindowfocuschanged, Onsaveinstancestate, onrestoreinstancestate methods:

1.onWindowFocusChanged method: Called when the activity form gets or loses focus, such as when it was created for the first time in front of the user. The activity is currently covered by other activity. The current activity goes to another activity or press the home key to go back to the main screen. The user exits the current activity. These are called onwindowfocuschanged, and are called after Onresume when the activity is created. When the activity is overwritten or retired from the background or the current activity exits, it is called after the OnPause and is seen:


This method is very practical 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, as the Form window object is not created yet, we need to get it in onwindowfocuschanged. Let's say you've already seen my Android animation frame animation This article will know that when trying to load frame animation in OnCreate failed because the Form window object is not initialized, So finally I put the code loaded into the animation in the onwindowfocuschanged, the problem solved.

It's just that people may wonder why I stare at it in the code, because I have it running log for each operation of the current activity, and I worry that it will affect the clarity of the whole process, so it's out of the question, and you just have to understand the application and the order of the operation.

2.onSaveInstanceState: (1) After activity is covered or retired from the background. The system has insufficient resources to kill it. This method is called, (2) when the user changes the screen orientation. This method is called, (3) when the current activity jumps to other activity or presses the home key to return to the main screen, it is back in the background. This method is called. In the first case, we cannot guarantee when it will happen, the system will be scheduled according to the level of resource stress; the other is that when the screen flips, the system destroys the current activity and then rebuilds a new one, and 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 the individual view components of the current form. The order in which the onsaveinstancestate is called precedes OnPause.

3.onRestoreInstanceState: (1) After activity is covered or retired from the background. The system does not have enough resources to kill it, and then the user returns to the activity, and this method is called, (2) when the user changes the screen orientation. This method is called during the rebuild process. We are able to override this method so that some temporary data can be recovered. The order in which the onrestoreinstancestate is called is after OnStart.

With a focus on three relatively unfamiliar methods, let's take a look at the activity and see what the life cycle is all about:

1. Start activity:


After the system has called OnCreate and OnStart. The Onresume is called, and since then the activity has entered the execution state.

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


We see that at this point the Onsaveinstancestate method was called before OnPause. And notice, back in the background, onpause after the onstop have been called.

3. Back to front desk from backstage:


When 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 enters the execution state.

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


Note Another situation is that we click on the button, just press the lock screen button, the effect of the operation is as above.

We noticed that. At this point the OnPause method of lifecycleactivity is called, and the OnStop method is not called, because the lifecycleactivity at this time does not retire to the background. is simply covered or locked; 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 execution state again.

6. Exit:


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

Everyone seems to notice. In all the process, there is no onrestoreinstancestate, this is not surprising, as we have said before, Onrestoreinstancestate only to kill the activity not in the foreground after the user returned to the activity , or the user changes the screen orientation of these two rebuilds during the call.

We are more difficult to demonstrate the first case, and we are able to demonstrate the detailed process in conjunction with another scenario. By the way, we also explain the change of the screen direction of the response strategy.

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

We are able to specify a specific direction for an activity, and then even turn the screen orientation after it is specified. The display direction also does not change:

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 frequently used approach that saves us a lot of unnecessary hassle. It's just that. What we're talking about today is the life cycle when the screen orientation changes. So we do not use fixed screen direction such a way.

Let's take a look at the life cycle of screen transitions in conjunction with an example, and we'll create a new activity named Orientationactivity, such as the following:

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 get into the "Settings->display". Select the "Auto-rotate screen" item. show that you can rotate the screen on your own initiative, and then we can test the process, and when we rotate the screen, we find that the system will destroy the current activity before rebuilding a new one:


The system first calls the Onsaveinstancestate method. We saved a temporary reference to the bundle object, and then we successfully took out the parameter after the activity was rebuilt.

In order to avoid the process of destroying the reconstruction, we need to orientationactivity the corresponding <activity> configuration in Androidmainfest.xml android:configchanges= " Orientation "and then we'll test it again. I tried to rotate it four times. Print For example the following:


Can see, each direction of rotation, only the Onconfigurationchanged method is called, there is no destruction of the reconstruction process.

Here are some points to note:

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

2. The simulator is very different from the real machine: The simulator assumes that the Android:configchanges property is not configured or the configuration value is orientation, cut to the horizontal screen to run a destruction--rebuild, cut to the vertical screen run two times. The real machine is one time. The simulator assumes that the configuration android:configchanges= "Orientation|keyboardhidden" (assuming Android4.0. This is "orientation|keyboardhidden|screensize"). Cut vertical screen operation onconfigurationchanged, cut horizontal screen run two times.

It's a real machine.

The life cycle of the activity program is closely related to the robustness, I hope my friends can experience serious, proficient.

Basic summary between articles: 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.