Android Foundation Summary: Activity lifecycle _android

Source: Internet
Author: User

Recently reviewed the life cycle of activity, see the relevant books and official documents, but also have a lot of gains, for the previous understanding has greatly improved, and here to share with you.

Friends familiar with Java EE are aware of the servlet technology, we want to implement a servlet of our own, 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 mechanism in Android is similar to the servlet, where the Android system is equivalent to a servlet container, the activity is the same as a servlet, and our activity is in this container, creating instances, initializing , destroying the instance and so on are all containers to invoke, which is called "Don" Call me, I ' ll called you. Mechanism.

Let's take a look at this classic life cycle flowchart:
I believe many friends have seen this flow chart, but also the basic understanding of the activity of the life cycle of several processes, we have to say that these several processes.

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

2. Current activity is covered or locked by other activity: The system calls the OnPause method to suspend execution of the current activity.

3. Current activity by the covered state back to the foreground or unlock screen: The system will call the Onresume method, again into the running state.

4. Current activity moves to the new activity interface or presses the home key back to the main screen, which itself is relegated to the background: The system calls the OnPause method first, then calls the OnStop method and goes to a standstill state.

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

6. The current activity is in the covered state or the background is not visible, that is, steps 2nd and 4th, the system is out of memory, killing the current activity, and then the user returns to the current activity: Call OnCreate method, OnStart method, Onresume method into the running state.

7. User exits Current activity: The system first calls the OnPause method, then calls the OnStop method, and finally calls the Ondestory method, ending the current activity.
But it's not enough to know, we have to test ourselves to get a thorough understanding.

Here's a couple of examples to illustrate the details of several processes in the lifecycle. We create a new project named Lifecycle, creating 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 = this; 
  
 private int param = 1; 
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate) is invoked when the activity is created; 
   
  LOG.I (TAG, "onCreate called."); 
   
  Setcontentview (r.layout.lifecycle); 
  Button btn = (button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {Intent Intent = n 
    EW Intent (context, targetactivity.class); 
   StartActivity (Intent); 
 } 
  }); 
  //activity is called @Override protected void OnStart () {Super.onstart () when it is created or returned from the background to the foreground; LOG.I (TAG, "OnStart CalleD. "); 
  The activity is called @Override protected void Onrestart () {Super.onrestart () when it is returned to the foreground from the background; 
 LOG.I (TAG, "Onrestart called."); 
  //activity is called @Override protected void Onresume () {super.onresume () when it is created or from being overwritten, back to the foreground in the background; 
 LOG.I (TAG, "Onresume called."); 
  //activity the window Gets or loses focus when it is called, after onresume or 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 it is overwritten below or when the screen is locked; 
  LOG.I (TAG, "OnPause called.");  It is possible to kill the activity after the OnPause or onstop has been executed, so it is necessary to save persistent data here////To exit the current activity or to jump to a new activity when it is called @Override protected 
  void OnStop () {super.onstop ();  
 LOG.I (TAG, "onStop called."); 
  When the active activity is called out, the activity ends after the call @Override protected void OnDestroy () {Super.ondestroy (); 
 LOG.I (TAG, "ondestory called."); /** * activity is called when it is killed by the system.
  * For example: when the screen direction changes, the activity is destroyed and rebuilt; The current activity is in the background and the system resources are strained to kill it. 
  * Also, the method is called when you jump to another activity or press home to return to the main screen, in order to save the state of the current view component. 
  * is invoked before onpause. 
  * * @Override protected void onsaveinstancestate (Bundle outstate) {outstate.putint ("param", param); LOG.I (TAG, "onsaveinstancestate called.") 
  Put param: "+ param); 
 Super.onsaveinstancestate (outstate); 
  /** * activity is called when it is killed and rebuilt by the system. 
  * For example: when the screen direction changes, the activity is destroyed and rebuilt; The current activity is in the background, the system resources are strained to kill it, and the user initiates the activity. 
  * In both cases onrestoreinstancestate will be invoked 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, onrestoreinstancestate methods:

1.onWindowFocusChanged method: Called when the activity window Gets or loses focus, for example, when it is first presented to the user; The current activity is overwritten by other activity The current activity goes to another activity or presses the home key to return to the main screen, itself to the background; the user exits the current activity. These situations invoke onwindowfocuschanged and are invoked after onresume when the activity is created, when the activity is overwritten or relegated to the background or the current activity exits, It is called after OnPause, as shown in the figure:
This approach can be useful in some situations, such as when a program starts to get the size of a particular view component, which may not be available in OnCreate, because the Windows window object has not yet been created, and this time we need to get the onwindowfocuschanged If you've seen my Android animation frame animation This article will know that the reason you tried to add a frame animation to OnCreate failed because the window Windows object was not initialized. So finally I put the code to load the animation into the onwindowfocuschanged, the problem is solved. But you may have doubts, why am I commenting it out in the code because there is an execution log for every action on the current activity, and I'm afraid it will affect the clarity of the entire process, so just take it out and you'll need to know the sequence of applications and execution.

2.onSaveInstanceState: (1) This method will be invoked when the activity is covered or relegated to the background and the system does not have enough resources to kill it; (2) This method is invoked when the user changes the screen orientation; (3) This method is invoked when the current activity jumps to another activity or presses the home key back to the main screen, which itself is relegated to the background. The first situation we can not guarantee when to occur, the system according to the degree of resource tension to dispatch; the second is when the screen flips the direction, the system destroys the current activity first, and then rebuilds a new one, and when we call this method, we can save some temporary data The third situation the system calls this method to save the state of the view components of the current window. The order of Onsaveinstancestate calls is before OnPause.

3.onRestoreInstanceState: (1) After the activity is overwritten or relegated to the background, the system resources are not enough to kill it, and then the user returns to the activity, this method will be called, (2) when the user changes the screen direction, the process of rebuilding, This method is invoked. We can override this method so that some temporary data can be recovered. The order of Onrestoreinstancestate calls is after OnStart.

After focusing on three relatively unfamiliar methods, let's take a look at the activity and see what the lifecycle is like:

1. Start activity:

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

2. Jump to another activity, or press the home key to return to the main screen:
We see that at this point the Onsaveinstancestate method was invoked before the OnPause, and note that the OnPause OnStop successively been invoked after the retreat back to the background.

3. Back to the front desk from the background:

When it comes to the foreground from the background, the system first calls the Onrestart method, then calls the OnStart method, and finally calls the Onresume method, and the activity goes into operation again.

4. Modify the configuration of targetactivity in Androidmanifest.xml and set the Android:theme property to @android:style/ Theme.dialog, and then click the button in Lifecycleactivity, the jump behavior becomes targetactivity overlay to lifecycleactivity, at this time the method is called:
Note that there is also a situation, we click on the button, just press the lock screen button, the effect is the same as above.

We note that at this point the Lifecycleactivity OnPause method is invoked and the OnStop method is not invoked because the lifecycleactivity at this time is not relegated to the background, but is overwritten or locked ; Onsaveinstancestate will be invoked before OnPause.

5. Press the rollback key to lifecycleactivity from being overwritten to the front, or press Ching to unlock the screen:
At this point only the Onresume method is invoked and goes directly into the running state.

6. Exit:

The last Ondestory method is invoked to mark the end of the lifecycleactivity.

Everyone seems to notice that in all of the process, there is no onrestoreinstancestate, this is not surprising, because we have said before, Onrestoreinstancestate is invoked only if the user returns to the activity after killing an activity that is not in the foreground, or if the user changes the screen orientation in both of these rebuilds. We want to demonstrate that the first situation is more difficult, we can combine the second situation to demonstrate the specific process. By the way, we will also explain the changes in the screen direction of the response strategy.

First, let's introduce the relevant knowledge about the activity screen direction.

We can specify a specific direction for an activity, specifying that the direction will not change following even if the screen direction is rotated:

1. Designated as the vertical screen: android:screenorientation= "Portrait" to the specified activity in Androidmanifest.xml or specified in the OnCreate method:

Setrequestedorientation (activityinfo.screen_orientation_portrait); Vertical screen 

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

Setrequestedorientation (Activityinfo.screen_orientation_landscape); Horizontal screen 

It is often used to set specific directions for the activity in the application, which can save us a lot of unnecessary trouble. However, we're talking today about the life cycle of changing the screen direction, so we don't use fixed screen orientation.

Let's take a look at the life cycle of the screen transformation with an example, 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 C"Alled. ");} 
  @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 invoked @Override public void onconfiguration when the direction changes 
  Changed (Configuration newconfig) {super.onconfigurationchanged (newconfig); 
  LOG.I (TAG, "onconfigurationchanged called."); Switch (newconfig.orientation) {case Configuration.ORIENTATION_PORTRAIT:setContentView (R.LAYOUT.ORIENTATION_PORTR 
   AIT); 
  Break Case ConfiguRation. 
   Orientation_landscape:setcontentview (R.layout.orientation_landscape); 
  Break 
 } 
 } 
}

First we need to go into "settings->display" and select "Auto-rotate screen" to show that we can automatically rotate the screens according to the direction, and then we can test the process, and when we rotate the screen, We found that the system would first destroy the current activity and then rebuild a new one:
The system first calls the Onsaveinstancestate method, we save a temporary parameter to the bundle object, and then we successfully remove the parameter after the activity is rebuilt.

To avoid this destruction of the reconstruction process, we need to orientationactivity the corresponding <activity> configuration in Androidmainfest.xml android:configchanges= " Orientation "and then we test it, I try to rotate it four times and print it as follows:
As you can see, each rotation direction, only the Onconfigurationchanged method is invoked, without the process of destroying the rebuild.

Here are a few things to note:

1. If the <activity> Android:screenorientation property is configured, the android:configchanges= "orientation" is invalidated.

2. Simulator and the real machine is very different: if the simulator does not configure the Android:configchanges property or the configuration value is orientation, cut to the horizontal screen to perform a destruction-> reconstruction, cut to the vertical screen execution two times. The true machine is all one time. If the android:configchanges= "Orientation|keyboardhidden" is configured in the emulator (if it is Android4.0, it is "orientation|keyboardhidden| ScreenSize "), cut the vertical screen to perform a onconfigurationchanged, cut the horizontal screen to perform two times. The true machine is all one time.

The life cycle of activity is closely related to the robustness of the program, and we hope that our friends can realize it and apply it skillfully.

Original link: http://blog.csdn.net/liuhe688/article/details/6733407

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.