An analysis of Android activity life cycle (I.)

Source: Internet
Author: User

?? Activity as one of the four components, the frequency is very high, basically we can see it everywhere in the Android, so in-depth understanding of activity, for the development of high-quality applications is very helpful. Today we will talk about the activity life cycle in detail so that we can be a duck in the future development.

First, the initial knowledge of activity

?? Activity is an interface that interacts with the user in everyday applications, and it provides a window into which the user completes the relevant operation. When we create activity in development, we call the Setcontentview (View) method to assign a layout interface to the activity, which is the interface that provides user interaction. The Android system manages activity through the activity stack, and the activity itself is managed by its own creation and destruction through the life cycle approach, so now let's look at how the activity lifecycle works.

Ii. the form of Activity

active/running:
Activity is active, at which point the activity is at the top of the stack and is visible to interact with the user.
Paused:
When the activity loses focus, or is a new non-full-screen activity, or is placed at the top of the stack by a transparent activity, the activity is converted to the paused state. But we need to understand that at this time the activity just lost the ability to interact with the user, all of its state information and its member variables are still there, only in the case of tight system memory, it is possible to be reclaimed by the system.
Stopped:
When an activity is completely covered by another activity, the covered activity enters the stopped state, which is no longer visible, but retains all of its state information and its member variables as the paused state does.
Killed:
When the activity is reclaimed by the system, the activity is in the killed state.
Activity will switch between the above four forms, as for how to switch, which varies depending on the user's operation. Having learned about the 4 forms of activity, we'll talk about the activity's life cycle.

Iii. Overview of Activity life cycle

Here, let's take a look at this classic life cycle flowchart:

?? I believe most people are not unfamiliar with this flowchart, well, the main topic we talk about is around this flowchart. We first have a general impression, after we analyze and then come back to see, it is quite clear.

Iv. Typical life cycle

?? The so-called typical life cycle is the normal life cycle process from creating, running, stopping, destroying, etc., with the participation of the user. Let's begin by introducing the timing of the invocation of several major methods, and then validating the invocation process through the code plane.
onCreate: This method is called when the activity is created, it is the first call to the life cycle method, we usually need to rewrite the method when creating the activity, and then do some initialization in the method, such as the resources to set the interface layout through Setcontentview, Initialization of the required component information, and so on.
OnStart: This method is called when the activity is being started and activity is already visible, but it is not displayed in the foreground and therefore cannot interact with the user. It can be simply understood that activity has been shown and we can't see it.
Onresume: When this method callback, the activity is already visible in the foreground, can interact with the user (in the Active/running form described above), the Onresume method and OnStart are the same point is both the activity is visible, Only the onstart callback when the activity or the background can not interact with the user, while the Onresume is displayed in the foreground, can interact with the user. Of course, from the flowchart, we can also see that when the activity stops (the OnPause method and the OnStop method are called), the Onresume method is also called back to the foreground, so we can also initialize some resources in the Onresume method, For example, reinitialize the resources released in the OnPause or OnStop method.
OnPause: When this method is called back, the activity is stopped (paused pattern), and in general the OnStop method is immediately recalled. But through the flowchart we can also see a situation is the OnPause method executes directly after the Onresume method, which is a more extreme phenomenon, this may be user action to the current activity back to the background and quickly return to the current activity, At this point, the Onresume method is recalled. Of course, in the OnPause method we can do some data storage or animation stop or resource recycling operations, but it can not be too time-consuming, because this may affect the display of new activity--onpause method execution completes, The new activity's Onresume method will not be executed.
OnStop: The general execution of the OnPause method executes directly, indicating that the activity is about to stop or be completely overwritten (stopped form), when activity is not visible and only runs in the background. Similarly, the OnStop method can do some resource-freeing operations (not too time consuming).
Onrestart: Indicates that the activity is restarting, and the method is called back when the activity is invisible to the visible state. This is generally the case when a user opens a new activity, the current activity is paused (OnPause and OnStop are executed), and then back to the current Activity page, the Onrestart method is recalled.
OnDestroy: Activity is being destroyed at this time, and is the last method of execution in the life cycle, in general we can do some recycling work in this method and the final release of resources.
In the following procedure, we validate several important cases in the above process, while observing the callback time of the life cycle method.

V. Verification of several major life cycle situations

Our case code is as follows:

 PackageCom.cmcm.activitylifecycle;ImportAndroid.content.Intent;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button; Public  class mainactivity extends appcompatactivity {Button BT;/** * is called when activity is created * @param savedinstancestate */    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); LOGUTILS.E ("OnCreate is Invoke!!!");        bt= (Button) Findviewbyid (R.ID.BT); Bt.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent i =NewIntent (mainactivity. This, Secondactivity.class);            StartActivity (i);    }        }); }/** * is called when activity is returned from the background back to the foreground * /    @Override    protected void Onrestart() {Super. Onrestart (); LOGUTILS.E ("Onrestart is Invoke!!!"); }/** *activity created or returned from the background back to the foreground is called */    @Override    protected void OnStart() {Super. OnStart (); LOGUTILS.E ("OnStart is Invoke!!!"); }/** *activity is created or called from the background and back to the foreground * /    @Override    protected void Onresume() {Super. Onresume (); LOGUTILS.E ("Onresume is Invoke!!!"); }/** * Activity is overwritten to the bottom or the lock screen is called */    @Override    protected void OnPause() {Super. OnPause (); LOGUTILS.E ("OnPause is Invoke!!!"); }/** * Called when exiting active activity or jumping to new activity    @Override    protected void OnStop() {Super. OnStop (); LOGUTILS.E ("OnStop is Invoke!!!"); }/** * is called when exiting the current activity, the activity ends after the call.    @Override    protected void OnDestroy() {Super. OnDestroy (); LOGUTILS.E ("OnDestroy is Invoke!!!"); }}
The next two of us analyze the invocation of several life cycle methods
  • 1. Let's start by analyzing the life-cycle methods that are called during activity startup, and run the program as follows:

    From log we can see that the activity started, called the OnCreate method first, then the OnStart method, and finally the Onresume method, into the running state, when the activity is displayed in the foreground. So
    Activity startup –>oncreate () –>onstart () –>onresume () is called in turn

  • 2. After the current activity is created, press the home key to return to the main screen. Operate as above:

    After the activity is created, when we click on the home Callback main screen, we can find that the OnPause method and the OnStop method are executed, that is, click the Home button to return to the main interface (activity is not visible) –>onpause () –> OnStop () is called sequentially

  • 3. When we click the Home button to return to the main interface and click the app again to return to activity, the result is as follows:
    We can find that when we go back to activity, we call the Onrestart method, the OnStart method, the Onresume method. So
    When we return to the original activity, –>onrestart () –>onstart () –>onresume () is called in turn

  • 4. When we play new activity on the basis of the original activity, the result of the call is as follows:

    We can see that the original activity called the OnPause method and the OnStop method. Other words
    In the original activity based on the new activity, the original activity life cycle execution Method order is –>onpause () –>onstop (), in fact, and click the Home button is the same. However, it is important to note that the current activity does not callback the OnStop method if the new activity uses a transparent theme. We also found that the new activity (secondactivity) life-cycle approach could only be called back after the OnPause method of the original activity was completed, which is why we said earlier that the OnPause method could not manipulate the time-consuming task.

  • 5 When we click Back to rewind, the callback results are as follows:

    From log we can see that when clicking the back key fallback, the equivalent of exiting the current activity,activity will be destroyed, so
    –>onpause () –>onstop () –>ondestroy () is called in turn when exiting the current activity

    Summary: Here we have a summary, when the activity starts, in turn calls OnCreate (), OnStart (), Onresume (), and when the activity is back in the background (not visible, Click Home or be completely overwritten by the new activity, OnPause () and OnStop () are called in turn. Onrestart (), OnStart (), and Onresume () are called in turn when activity is returned to the foreground (from the desktop back to the original activity or overwritten and back to the original activity). When activity exits destruction (click the Back Key), OnPause (), OnStop (), OnDestroy () are called sequentially, and the entire lifecycle method callback for the activity is completed. Now we look back at the previous flowchart, it should be quite clear. Well, that's the typical life cycle process of activity. Next we'll talk about the abnormal life cycle of activity.


    An analysis of Android activity life cycle (II.)



    Main reference books:
    Explore the art of Android development
    "Advanced Android Development"
    "Google official website"

An analysis of Android activity life cycle (I.)

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.