A deep understanding of the life cycle of activity in Android development _android

Source: Internet
Author: User

What is an activity
first, the activity is one of the four components of the Android system that can be used to display view. An activity is a system module that interacts with the memory, and almost all activity interacts with the user, but it is not correct to say that the activity is mainly used to show view.

Before we dive into the activity, we need to know about the MVC design pattern, which is already classic in Java EE, and the points are quite clear, but in Android many people are not very clear about the application of MVC in Android development, Let me first introduce the application of MVC in Android development:

M (model): Model is the main part of the application, all business logic should be written here, in the Android model layer and Java EE in the changes are not very small, such as: the operation of the database, network and other operations are placed on this layer (but not that they are all in the same package, Can be divided into open, but they collectively referred to as the model layer.
V. (view view): Is the part of the application that is responsible for generating the user interface, and is the only layer that the user can see in the entire MVC architecture, receiving user input and displaying the processing results; In the Android application, the description of the interface in the XML file is generally used, which can be easily introduced. Of course, you can use javascript+html and other ways as view.
C (Controller control Layer) the responsibility of the Android control layer will fall on the shoulders of many activities, so it is recommended that you do not write too much code in the activity, as far as possible to do the task of delivery model business Logic layer processing.

Well, after introducing the MVC architecture in Android application development, we can be very clear that the activity in Android is primarily for control, it can select the view to display, you can get data from view, and then pass the data to the model layer for processing. , and finally to show the processing results.

Activity life cycle
So, let's take a look at the life cycle of the activity. I want to learn the servlet's children's shoes know that we were learning the servlet also from the life cycle began, first know the order of the request, and then know how to handle the request. Only in this way can we do something relevant when we need it.
The same is true with Android learning, where activity is the most important of Android, and typically an interface, so that if we need to do anything, we need to deal with the activity. Let's look at the specific code below.
1 Build a project first, the name is random. Activity is also casual, anyway, you can understand the OK.
I built a structure as shown here:

The name here is casual, do not have to pursue the same.
2 You see I have two activity, before also said activity is an interface, then two of course is two interface.
Before we look at the code, let's look at the methods of activity events, as follows:

public void OnCreate (Bundle savedinstancestate); 
public void OnDestroy (); 
public void OnPause (); 
public void Onrestart (); 
public void Onresume (); 
public void OnStart (); 
public void OnStop (); 

These methods, we look at the method name and presumably we can guess when the method was invoked. But the real understanding is not so simple.
Let's start with our topic and see the code.
First look at Strings.xml, which defines the string we need to display.

<?xml version= "1.0" encoding= "Utf-8"?> 
<resources> 
 <string name= "Hello" >hello world, mainactivity!</string> 
 <string name= "app_name" >activity life cycle </string> 
 <string name= " Other "> Another activity</string> 
 <string name=" Start "> Start another activity</string> 
 < String name= "Stop" > End current activity</string> 
</resources> 

The front two are optional, but not modified after creation.
Let's take a look at the XML of the interface:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
 android:orientation=" vertical " 
 android:layout_width=" fill_parent " 
 android:layout_" height= "Fill_parent" 
 > 
 <button 
  android:layout_width= "wrap_content" 
  android:layout_height = "Wrap_content" 
  android:text= "@string/start" 
  android:id= "@+id/start" 
  /> <button Android:layout_width= "Wrap_content" 
  android:layout_height= "wrap_content" 
  android:text= "@string/stop" 
  android:id= "@+id/stop" 
  /> 
</LinearLayout> 

Here you should probably all understand, very simple, just two buttons, one is to start another activity, the other is to stop the current activity. Very simply, if you don't understand this, you need to first add the basics of Android.
Another one is androidmanifest.xml this is the most important, because we use two activity, two all need to be "registered" here, otherwise will not be used.

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Com.shun.android "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android: minsdkversion= "7"/> <application android:icon= "@drawable/icon" android:label= "@string/app_name" > <acti Vity android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action android:name=" android.i Ntent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-filter&gt 
  ; </activity> <activity android:name= ". Otheractivity "android:label=" @string/other "> <intent-filter> <action android:name=" Android.int 
  Ent.action.MAIN "/> <category android:name= android.intent.category.LAUNCHER"/> </intent-filter> 
 </activity> </application> </manifest>

  Note that the order of activity here is related to the order in which you started, I need to start with mainactivity, so I put it in front of otheractivity.
 3) Here we have finished with the interface code, and the next step is our main code. Mainactivity and Otheractivity. We start by mainactivity. Click to start another activity to start the otheractivity. Stop to stop the current activity accordingly.
  Below is the code for mainactivity:

Package com.shun.android; 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.util.Log; 
Import Android.view.View; 
 
Import Android.widget.Button; 
 public class Mainactivity extends activity {private static final String TAG = "mainactivity"; 
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
   
  Setcontentview (R.layout.main); 
   
  LOG.I (TAG, "onCreate"); 
  Button start = (Button) Findviewbyid (R.id.start); Start.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {Intent Intent = new inte 
    NT (Mainactivity.this,otheractivity.class); 
    StartActivity (Intent); 
   MainActivity.this.finish (); 
   
  } 
  }); 
  Button stop = (button) Findviewbyid (r.id.stop); Stop.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {MainActivity.this.finish ( 
   ); 
   
 } 
  }); } protected void OnDestroy () {log.i (TAG, "OnDestroy"); 
 Super.ondestroy (); 
  } protected void OnPause () {log.i (TAG, "OnPause"); 
 Super.onpause (); 
  } protected void Onrestart () {log.i (TAG, "Onrestart"); 
 Super.onrestart (); 
  } protected void Onresume () {log.i (TAG, "Onresume"); 
 Super.onresume (); 
  } protected void OnStart () {log.i (TAG, "OnStart"); 
 Super.onstart (); 
  } protected void OnStop () {log.i (TAG, "onStop"); 
 Super.onstop (); 
 } 
}

The

  otheractivity code is as follows:

Package com.shun.android; 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.util.Log; 
Import Android.view.View; 
 
Import Android.widget.Button; 
 public class Otheractivity extends activity{private static final String TAG = "otheractivity"; 
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
   
  Setcontentview (R.layout.main); 
   
  LOG.I (TAG, "onCreate"); 
  Button start = (Button) Findviewbyid (R.id.start); Start.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {Intent Intent = new inte 
    NT (Otheractivity.this,mainactivity.class); 
    StartActivity (Intent); 
   OtherActivity.this.finish (); 
   
  } 
  }); 
  Button stop = (button) Findviewbyid (r.id.stop); Stop.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {OtherActivity.this.finish 
   (); 
   
 } 
  }); } protected void OndesTroy () {log.i (TAG, "OnDestroy"); 
 Super.ondestroy (); 
  } protected void OnPause () {log.i (TAG, "OnPause"); 
 Super.onpause (); 
  } protected void Onrestart () {log.i (TAG, "Onrestart"); 
 Super.onrestart (); 
  } protected void Onresume () {log.i (TAG, "Onresume"); 
 Super.onresume (); 
  } protected void OnStart () {log.i (TAG, "OnStart"); 
 Super.onstart (); 
  } protected void OnStop () {log.i (TAG, "onStop"); 
 Super.onstop (); 
 } 
  
}

The code has nothing to say, it's simple. It's important to understand the life cycle.
Let's look at the effect of the operation:
When we start:

It starts OnCreate first, followed by OnStart, then Onresume. These three specific, no doubt.
The interface is as follows:

Then we click to start another activity to see the effect, here is mainactivity, click will jump to otheractivity.
Let's look at the effect:

This has been jumped to another activity because we used the same layout, so the display is the same, but the title is not the same.
Let's take a look at its information:

We see that mainactivity will pause first and then create a new activity, and then call destroy Mainactivity when the creation is complete.

Everyone would suspect, because I wrote the finish in the mainactivity behind the startactivity, which is definitely the reason for calling stop in the back. First of all not sure so fast, let's put the finish to the front to see.
We modify some of the code in the OnCreate in mainactivity to the following:

Start.setonclicklistener (New View.onclicklistener () {public 
    
   void OnClick (View v) { 
    MainActivity.this.finish (); 
    Intent Intent = new Intent (mainactivity.this,otheractivity.class); 
    StartActivity (intent); 
   } 
  ); 

Here we put the finish in front, we rerun to see the effect:

We see the effect is the same. However, for the readability of the code, it is advisable to put it back in order to conform to the call sequence of the lifecycle.

Now that we're in otheractivity, do we want to go back to mainactivity, or do we start another activity as well:

The call procedure here is also the same, first paused, created, and finally destroyed.
Now we directly close the mainactivity there:

Here we see that it calls the OnPause method first, then the formal stop and destroy. From here we suspect that when an activity is switched, the OnPause method of the current activity is invoked first. Here, we do not say is not correct, then go to see, practice to prove everything.

4 We have manually finished this activity in front, and below we are not over, let's look at the modified code:
Otheractivity will still call finish to destroy this page, because it doesn't need to.
Otheractivity is as follows:

Button start = (Button) Findviewbyid (R.id.start); 
  Start.setonclicklistener (New View.onclicklistener () {public 
    
   void OnClick (View v) { 
    OtherActivity.this.finish (); 
   } 
  ); 
 Mainactivity is as follows:
button start = (Button) Findviewbyid (R.id.start); 
  Start.setonclicklistener (New View.onclicklistener () {public 
    
   void OnClick (View v) { 
    Intent Intent = new Intent ( Mainactivity.this,otheractivity.class); 
    StartActivity (intent); 
   } 
  ); 

This way we can change it, and we don't need to change it anywhere else.
Let's look at the effect, and when we start mainactivity, we click to start another activity to start otheractivity, and we'll look at the information:

We see that it doesn't call OnDestroy, which means that this ondestroy is called when we call the Finish method.
Here we click Start another activity in otheractivity to start another activity, note that the "boot" here is not really booting, not started by startactivity, just ending the current activity.
Let's look at the information:

Here we click to start another activity and actually just stop the current otheractivity. Let's look at the printed information:

Here we see that it is not the OnCreate method of invoking Mainactivity, because Mainactivity is not destroyed, it just stops. When the otheractivity is destroyed, the mainactivity is restarted when it is switched. Then the Onrestart is invoked.

5 note, we are here to take otheractivity as a whole activity, that is, the entire interface. Let's look at another scenario where we started a dialog box.
We need to modify the Androidmanifest.xml, as follows:

<activity android:name= ". Otheractivity " 
     android:label=" @string/other " 
     android:theme=" @android: Style/theme.dialog "> 
  </ Activity> 

Just modify the definition of otheractivity, where we define it as a dialog, a dialog type, which does not occupy the entire interface, and the original activity runs backwards into the background.
For the demonstration of the effect, we first remove the finish code from the other activity in the mainactivity and remove the code from the otheractivity to start another activity, leaving the finish code. This allows you to see the effect of the reboot.
The following code is removed:
Some of the code in Mainactivity:

Button start = (Button) Findviewbyid (R.id.start); 
  Start.setonclicklistener (New View.onclicklistener () {public 
    
   void OnClick (View v) { 
    Intent Intent = new Intent ( Mainactivity.this,otheractivity.class); 
    StartActivity (intent); 
   } 
  ); 

Code in Otheractivity:

Button start = (Button) Findviewbyid (R.id.start); 
  Start.setonclicklistener (New View.onclicklistener () {public 
    
   void OnClick (View v) { 
    OtherActivity.this.finish (); 
   } 
  ); 

After we run click Start another activity can see:

Here we see that mainactivity only calls a onpause, which means it doesn't stop, it just runs in the background.
We see the effect:

We see that the activity of the Lord runs behind and forms a translucent state, which is running in the background.
When we click to start another activity, note that we do not start another activity here, but just end the current activity directly.
Now when we click to start another activity, the current otheractivity closes and goes back to the original mainactivity.
Let's look at the effect:

and backstage information is as follows:

It directly calls Onresume to restore the mainactivity instead of restarting it. This is because Mainactivity is still running in the background, we do not need to restart one.

In fact, this life cycle is not difficult, the difficulty is to understand each stage. As more and more contacts are being contacted, it is believed that the understanding of this cycle will be more and more profound.
Here's a map of the official Android lifecycle:

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.