Analysis of Android's Activity Life Cycle

Activity is an interface that interacts with users. It provides a window for users to complete related operations. Users can click, slide and other operations.

Reprinted:    http://blog.csdn.net/javazejian/article/details/51932554

 
 

Reprinted: https://blog.csdn.net/javazejian/article/details/51932554

As one of the four major components, Activity appears quite frequently. Basically, we can see its traces everywhere in android. Therefore, a deep understanding of Activity is very helpful for developing high-quality applications. Today we will talk about the life cycle of Activity in detail, so that we can feel like a duck in water in the future development.

1. Getting to know Activity

  In daily applications, Activity is the interface that interacts with the user, which provides a window for the user to complete related operations. When we create an Activity in development, we specify a layout interface for the Activity by calling the setContentView(View) method, and this interface is the interface provided for user interaction. In the Android system, Activity is managed through the Activity stack, and Activity itself manages its own creation and destruction through the method of the life cycle. In this case, now let's take a look at how the Activity life cycle works.

2. The form of Activity

Active/Running:  The Activity is in an active state. At this time, the Activity is at the top of the stack, is visible, and can interact with the user. Paused:  When the Activity loses focus, or is placed on the top of the stack by a new non-full-screen Activity, or by a transparent Activity, the Activity transitions to the Paused state. But we need to understand that at this time, Activity just loses the ability to interact with the user, and all its state information and member variables still exist. Only when the system memory is tight can it be recycled by the system. Stopped:  When an Activity is completely covered by another Activity, the covered Activity will enter the Stopped state, at which point it is no longer visible, but retains all its state information and member variables like the Paused state. Killed:  When the Activity is recycled by the system, the Activity is in the Killed state. Activity will switch among the above four forms. As for how to switch, it varies depending on the user's operation. After understanding the four forms of Activity, let's talk about the life cycle of Activity.

3. Activity life cycle overview

Here, let's take a look at this classic life cycle flow chart:     I believe most people are not unfamiliar with this kind of flow chart. Well, the main topic we will talk about below is this flow chart. We have a general impression first, and then we will look back after the analysis, and it will be quite clear.

4. Typical life cycle

  The so-called typical life cycle is that in the case of user participation, Activity goes through the normal life cycle process from creation, running, stopping, destruction and so on. Let's first introduce the calling timing of several main methods, and then verify the calling process through the code level. onCreate  : This method is called back when the Activity is created. It is the first method called in the life cycle. We generally need to override this method when creating an Activity, and then do some initialization operations in this method, such as through setContentView Set the resources of the interface layout, initialize the required component information, etc. onStart  : When this method is called back, it means that the Activity is starting. At this time, the Activity is already in a visible state, but it has not been displayed in the foreground, so it cannot interact with the user. It can be simply understood that the Activity has been displayed and we cannot see the pendulum. onResume  : When this method is called back, it means that the Activity is visible in the foreground and can interact with the user (in the Active/Running state mentioned above). The onResume method and onStart are similar in that both indicate that the Activity is visible, but When onStart is called back, the Activity is still in the background and cannot interact with the user, while onResume has been displayed in the foreground and can interact with the user. Of course, from the flow chart, we can also see that when the Activity is stopped (the onPause method and the onStop method are called), the onResume method will also be called when it returns to the foreground, so we can also initialize some resources in the onResume method, such as re-initialization Resources released in onPause or onStop methods. onPause : When this method is called back, it means that the Activity is being stopped (Paused state). In general, the onStop method will be called back immediately. But through the flow chart, we can also see that a situation is that the onResume method is directly executed after the onPause method is executed. This is a relatively extreme phenomenon. This may be that the user operation makes the current Activity retreat to the background and then quickly returns to the background. For the current Activity, the onResume method will be called back. Of course, in the onPause method, we can do some data storage or animation stop or resource recycling operations, but it should not be too time-consuming, because this may affect the display of the new Activity - after the onPause method is executed, the new Activity's onResume method will be executed. onStop  : Generally, it is executed directly after the execution of the onPause method, indicating that the Activity is about to stop or is completely covered (Stopped state). At this time, the Activity is invisible and only runs in the background. Similarly, some resource release operations can be done in the onStop method (not too time-consuming). onRestart  : Indicates that the Activity is restarting. When the Activity changes from invisible to visible, this method is called back. In this case, when the user opens a new Activity, the current Activity will be suspended (onPause and onStop are executed), and then when the user returns to the current Activity page, the onRestart method will be called back. onDestroy  : At this time, the Activity is being destroyed, and it is also the last method executed in the life cycle. Generally, we can do some recycling work and final resource release in this method. Next, we use the program to verify several important situations in the above process, and observe the callback timing of the life cycle method.

5. Verify several major life cycle situations

Our case code is as follows:

package com.cmcm.activitylifecycle;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button bt;

    /**
     * Activity创建时被调用
     * @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(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(i);
            }
        });
    }


    /**
     * Activity从后台重新回到前台时被调用
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtils.e("onRestart is invoke!!!");
    }

    /**
     *Activity创建或者从后台重新回到前台时被调用
     */
    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.e("onStart is invoke!!!");
    }


    /**
     *Activity创建或者从被覆盖、后台重新回到前台时被调用
     */
    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.e("onResume is invoke!!!");
    }

    /**
     *  Activity被覆盖到下面或者锁屏时被调用
      */
    @Override
    protected void onPause() {
        super.onPause();
        LogUtils.e("onPause is invoke!!!");
    }

    /**
     *退出当前Activity或者跳转到新Activity时被调用
     */
    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.e("onStop is invoke!!!");
    }

    /**
     *退出当前Activity时被调用,调用之后Activity就结束了
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.e("onDestroy is invoke!!!");
    }
}下面我们俩综合分析几种生命周期方法的调用情况
  • 1.我们先来分析Activity启动过程中所调用的生命周期方法,运行程序截图如下: 
    Snip20160716_2 
    从Log中我们可以看出Activity启动后,先调用了onCreate方法,然后是onStart方法,最后是onResume方法,进入运行状态,此时Activity已在前台显示。因此, 
    Activity启动–>onCreate()–>onStart()–>onResume()依次被调用

  • 2.当前Activity创建完成后,按Home键回到主屏。按如上操作运行截图: 
    Snip20160716_4 
    我们在Activity创建完成后,点击Home回调主界面时,可以发现此时onPause方法和onStop方法被执行,也就是点击Home键回到主界面(Activity不可见)–>onPause()–>onStop()依次被调用

  • 3.当我们点击Home键回到主界面后,再次点击App回到Activity时,调用结果如下:Snip20160716_5 
    我们可以发现重新回到Activity时,调用了onRestart方法,onStart方法,onResume方法。因此, 
    当我们再次回到原Activity时–>onRestart()–>onStart()–>onResume()依次被调用

  • 4.当我们在原有的Activity的基础上打新的Activity时,调用结果如下: 
    Snip20160716_6 
    我们可看到原来的Activity调用的了onPause方法和onStop方法。也就是说 
    在原Activity的基础上开启新的Activity,原Activity生命周期执行方法顺序为–>onPause()–>onStop(),事实上跟点击home键是一样的。但是这里有点要注意的是如果新的Activity使用了透明主题,那么当前Activity不会回调onStop方法。同时我们发现新Activity(SecondActivity)生命周期方法是在原Activity的onPause方法执行完成后才可以被回调,这也就是前面我们为什么说在onPause方法不能操作耗时任务的原因了。

  • 5 当我们点击Back键回退时,回调结果如下: 
    Snip20160716_7
    从Log我们可以看出,当点击Back键回退时,相当于退出了当前Activity,Activity将被销毁,因此 
    退出当前Activity时–>onPause()–>onStop()–>onDestroy()依次被调用

    小结:到这里我们来个小结,当Activity启动时,依次会调用onCreate(),onStart(),onResume(),而当Activity退居后台时(不可见,点击Home或者被新的Activity完全覆盖),onPause()和onStop()会依次被调用。当Activity重新回到前台(从桌面回到原Activity或者被覆盖后又回到原Activity)时,onRestart(),onStart(),onResume()会依次被调用。当Activity退出销毁时(点击back键),onPause(),onStop(),onDestroy()会依次被调用,到此Activity的整个生命周期方法回调完成。现在我们再回头看看之前的流程图,应该是相当清晰了吧。嗯,这就是Activity整个典型的生命周期过程。下篇我们再来聊聊Activity的异常生命周期









Android 横竖屏切换的生命周期

以下别人的总结,引用一下:

1、不设置Activity的android:configChanges时,切屏会重新调用各个生命周期,切横屏时会执行一次,切竖屏时会执行两次

2、设置Activity的android:configChanges="orientation"时,切屏还是会重新调用各个生命周期,切横、竖屏时只会执行一次

3、设置Activity的android:configChanges="orientation|keyboardHidden"时,切屏不会重新调用各个生命周期,只会执行onConfigurationChanged方法




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325894984&siteId=291194637