Full lifecycle examples of activity in Android programming _android

Source: Internet
Author: User
Tags stub

An example of this article is the complete lifecycle of activity in Android programming. Share to everyone for your reference, specific as follows:

The activity in Android has its own lifecycle, and learning about it can help us better understand some of the mistakes we've encountered when we write our programs in the future. This article is very long, hope not to delay everyone's time ~

There's not much to do today about the activity stack, which is mainly about the life cycle of the activity itself.

Distinguish between several concepts

1 The official explanation for the activity was "an activity was anapplication component that provides a screens with which users can interact in Orde R to doing something, such as dial the phone, take a photo, send an email, or view a map. each of the activity is given a windows in which to draw its user interface. "That is, each window that the user interacts with, an operation that the user is currently doing."

2 Back-stack user through the touch program will launch an activity A through the Application launcher, starting activity A will be pushed onto the top of the stack, if the current activity a starts a new activity B, So at this point a calls the OnStop function, and the system maintains the activity information. When the user presses the back key, back stack will perform a pop operation, and call a onresume () specific to the stack details, which will be described in detail later.

3 Tasks When the user is in a activi: Activity A When the name "TaskOne application Ty, press the home key user back to the launcher, at this point, if the user touches the new application, then create a new task, a back Stack represents a task. The activity of the different programs can be pressed into the same stack, that is to say, you can form a task, such as your program to start a system with the text of a message, the user's feeling is to send a text message seems to be a function of your program.

Note: The above behavior is the system's default settings, there are two ways to change the behavior of the activity, add a to start B, one in the B manifest settings, change behavior, The other is to specify the activity settings to start in the activity-initiated intent, where the intent priority is higher than the manifest.xml file, and some modes are not in both ways at the same time .

The Android lifecycle includes onCreate onStart onrestart onresume onpause onStop, where the activity invokes the above methods in the declaration cycle to perform operations of different states. The call time for each method is described below

OnCreate () The activity cannot be terminated in the second state
called the activity is the created. This is where you should does all of your normal static set up:create views, bind data to lists, etc. This method also provides for you and a Bundle containing the activity ' s previously frozen state, if there is one.

Always followed by OnStart ().
//When the activity is first created, it is called. You should do all the static creation in this method, create views, bind data to lists (by Setcontnetview method), and so on. If there is a saved state, the method also provides you with a bundle that contains the most recent state of the activity. The OnStart method always calls after this method

Onrestart () The activity cannot be terminated in the second state
called after the your activity has been stopped, prior to it being started.
Always followed by OnStart ()
//Called after your activity has stopped, call before starting again

Onresume () The activity cannot be terminated in the second state
called the activity would start interacting with the user. At the ' point ' your the activity stack, with user input going to it.
Always followed by OnPause ().
//The activity will be invoked when it is started interacting with the user. At the moment your activity is at the top of the activity stack, for user input, always///after OnPause is called

OnPause () The activity cannot be terminated in the secondary state, except for the Android honeycomb system
called the ' system is ' about to-start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things G CPU, etc. Implementations of this method must is very quick because the next activity is not is resumed until this method returns.
followed by either Onresume () if the activity is returns back to the front, or onStop () if it becomes invisible to the user.

It is called when the system is about to restart its previous activity (not understood, it is understood: when the current activity is called to start a new activity), the typical application is to submit the unsaved data to the current data (meaning to save the data update), Stop animations and other potentially CPU-intensive operations. The implementation of this method must be quick because the next activity will not be restarted until this method returns.

The Onresume method is invoked after the OnPause method when the activity is transferred from the back (improper translation background) to the front (the state of the user interaction)

When an activity becomes invisible, the OnStop method is invoked after OnPause

OnStop () The activity can be terminated in the secondary state
Called when the "is no longer visible to the" user, because another activity has been and are resumed Ring this one. This may happen either because a new to being started, a existing one is being brought in front to this one, or This is being destroyed.
followed by either Onrestart () If this activity is coming back to interact with the user, or OnDestroy () is going away.

is invoked when the activity is no longer visible to the user because another activity has restarted and overwritten the current activity (on the stack). When a new activity is initiated, or an existing activity is returned to the foreground, or the current activity is destroyed. If the activity is to return to the foreground and the user to interact, call the Onreatart method after this method, and the OnDestroy method will be invoked after this method if the current activity is to die

OnDestroy () The activity can be terminated in the secondary state
The final call to receive before your the activity is destroyed. This can happen either because the "activity is finishing" someone called Finish () on it, or because the system is Temporar Ily destroying this instance's activity to save space. You can distinguish between this two scenarios with the Isfinishing () method.

This is the last method to receive when your activity is extinct. There are two scenarios for calling this method: one is that the activity will be completed, and it can be implemented by calling the finish method. Instead, the system destroys instances of the activity to free up space. You can use the Isfinish method to distinguish between two situations. This method is commonly used in OnPause methods to determine whether an activity is paused or terminated. The following demo will demonstrate this feature.

The image below is a life cycle demo of the official website.

Okay, let's take a look at one of the demo examples I've written,

Mainfest.xml

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= 
"http://schemas.android.com/apk/res/" Android " 
   package=" uni.activity " 
   android:versioncode=" 1 " 
   android:versionname=" 1.0 "> 
  < USES-SDK android:minsdkversion= "7"/> 
  <application android:icon= "@drawable/icon" android:label= "@string App_name "> 
    <activity android:name=". Activitydemoactivity " 
         android:label=" @string/app_name "> 
      <intent-filter> 
        <action Android:name= "Android.intent.action.MAIN"/> 
        <category android:name= "Android.intent.category.LAUNCHER" "/> 
      </intent-filter> 
    </activity> 
    <activity android:name=". Activity01 " 
         android:label=" @string/app_name "> 
    </activity> 
  </application> 
</manifest>

Layout file Main.xml

<?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" 
  > 
<textview  
  android:layout_width= "fill_parent"  
  android:layout_ height= "Wrap_content"  
  android:text= "@string/hello"/> <button android:id=  
  "@+id/button _a " 
  android:text=" go to Activity 2 " 
  android:layout_width=" fill_parent " 
  android:layout_height=" wrap _content " 
  /> 
</LinearLayout>

Activity01.xml

<?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" 
  > 
<textview  
  android:layout_width= "fill_parent"  
  android:layout_ height= "Wrap_content"  
  android:text= "@string/hello"/> <button android:id=  
  "@+id/button _a " 
  android:text=" go to Activity 2 " 
  android:layout_width=" fill_parent " 
  android:layout_height=" wrap _content " 
  /> 
</LinearLayout>

String.xml

<?xml version= "1.0" encoding= "Utf-8"?> 
<resources> 
  <string name= "Hello" >hello world, activitydemoactivity!</string> 
  <string name= "app_name" >ActivityDemo</string> 
  < String Name= "Activity01" >this is activity 01</string> 
</resources>

Activitydemoactivity.java

* * * @author Octobershiner * SE. 
HIT * Demonstrates the complete activity's declaration cycle, and the invocation of the Isfinish method * This activity is the program entry activity * * * */package uni.activity; 
Import android.app.Activity; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.util.Log; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; The public class Activitydemoactivity extends activity {/** called the ' when the ' is the ' is ' the ' activity ' is a-created private Stati 
  C final String TAG = "Demo"; 
  Private Button button_a; 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    Button_a = (Button) This.findviewbyid (r.id.button_a); 
  Button_a.setonclicklistener (New Mybuttonlistener ()); Private class Mybuttonlistener implements onclicklistener{@Override public void OnClick (View v) {/ /TODO auto-generated Method stub Intent Intent = new Intent (); 
      Intent.setclass (Activitydemoactivity.this, Activity01.class); 
      ActivityDemoActivity.this.startActivity (Intent); 
    Interested friends can cancel the following code comments to test the use of the finish method, will find that the first activity will be forced to terminate//activitydemoactivity.this.finish (); 
  } 
  }; 
    protected void OnStart () {Super.onstart (); 
  LOG.I (TAG, "the Activitydemo State---->onstart"); 
    } protected void Onrestart () {Super.onrestart (); 
  LOG.I (TAG, "the Activitydemo State---->onreatart"); 
    } protected void Onresume () {super.onresume (); 
  LOG.I (TAG, "the Activitydemo State---->onresume"); 
    } protected void OnPause () {super.onpause (); 
    Call the Isfinishing method to determine whether the activity is to destroy LOG.I (TAG, "the Activitydemo State---->onpause"); 
    if (isfinishing ()) {LOG.W (TAG, "The Activitydemo would be destroyed!"); 
    }else{LOG.W (TAG, "The Activitydemo is just pausing!"); 
    } protected void OnStop () {super.onstop (); LOG.I (TAG, "the Activitydemo state---->onstop "); 
    } protected void OnDestroy () {Super.ondestroy (); 
  LOG.I (TAG, "the Activitydemo State---->ondestroy");

 } 
}

Activity01.java

* * * @author Octobershiner * SE. 
HIT * Demo complete activity declaration cycle, and Isfinish method invocation * This activity can be initiated by activitydemoactivity * * * * * * * * * * * * * * * * * * * * * uni.activity 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.util.Log; 
  public class Activity01 extends activity{private static final String TAG = "Demo"; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub Super.oncre 
    Ate (savedinstancestate); 
    Setcontentview (R.LAYOUT.ACTIVITY01); 
  LOG.D (TAG, "the ACTIVITY01 State---->onstart"); 
      } protected void OnStart () {Super.onstart (); 
    LOG.D (TAG, "the ACTIVITY01 State---->onstart"); 
      } protected void Onrestart () {Super.onrestart (); 
    LOG.D (TAG, "the ACTIVITY01 State---->onreatart"); 
      } protected void Onresume () {super.onresume (); 
    LOG.D (TAG, "the ACTIVITY01 State---->onresume"); } protected void OnPause () {SUPER.ONpause (); 
      LOG.D (TAG, "the ACTIVITY01 State---->onpause"); 
      Call the Isfinishing method to determine whether the activity is to destroy if (isfinishing ()) {LOG.W (TAG, "The activity01 will be destroyed!"); 
      }else{LOG.W (TAG, "The activity01 is just pausing!"); 
      } protected void OnStop () {super.onstop (); 
    LOG.D (TAG, "the ACTIVITY01 State---->onstop"); 
      } protected void OnDestroy () {Super.ondestroy (); 
    LOG.D (TAG, "the ACTIVITY01 State---->ondestroy"); 

 } 
}

Here is the result of the demo,

The operation process is: Start activitydemoactivity

Then click the button to enter the ACTIVITY01

(visible activity first paused and will not be released, is actually a new activity presses the stack process, then the new activity starts, should be oncreate then OnStart, I print the statement to write wrong, the careful friend should see, when the old activity is not visible , call its OnStop method)

And then press the return key back to Activitydemoactivity

(After returning, the activity01 at the top of the stack will perform the stack operation, the display will be destroy)

Then press the return key to return to the desktop

In fact, the East evil is not complex to write a bit longer, but basically shows the complete life cycle of the activity.

I hope this article will help you with the Android program.

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.