Activity life cycle of Android view manual

The Android View Handbook is a theoretical article that I hope to provide a clear and easy-to-understand explanation of the basic knowledge of Android based on Google's official documents by combining graphics and text. Internally try not to use long codes for interpretation, and more hope to understand Android-related knowledge from the perspective of graphic and text flow, so that readers can easily understand, understand and review quickly. It is a basic manual based on theory. .
Applicable personnel: Novices who need a general understanding of relevant knowledge when they are initially exposed to Android theory; veterans who have several years of development experience and need to quickly review basic knowledge.
In the article, some interview questions will also be combined to achieve self-answering of knowledge, consolidate the knowledge of the article, and facilitate the students who need to interview to quickly review the basic knowledge.

The first activity life cycle

Everything is difficult at the beginning. A man who looks very similar to me, Peng Yuyan, once said that if you set yourself a plan for 40 minutes, but you only realized 5 minutes of it, this is your problem, because you can I can't control myself, how to influence the outside world, to change every stage of my life.
And the life cycle of Activity is the process of each stage of Activity in the four major components of our application. It lets us know the state of Activity during execution and what we should do during execution. .

overview

Activity instances in an application transition between different states in its lifecycle as the user browses, exits, and returns to the application. The Activity class provides a number of callbacks that let the Activity know that a state has changed: the system is creating, stopping, or resuming an Activity, or is destroying the Activity's process. Through the life cycle, we can know the current state of the Activity and process it accordingly.

Activity life cycle diagram

The life cycle diagram is the first diagram that many students who are getting started with Android come into contact with, and it is also a relatively important diagram in the concept knowledge of Android. I will also describe its various stages and general functions in the following diagram.
insert image description here

Activity life cycle main method (main link)

The main method of the life cycle is the main link involving various life states in the middle of the above figure, and it is also the process of calling some methods that an Activity mainly goes through.

  • onCreate()
    will trigger this method when the Activity is created for the first time , and the Activity will enter the "Created" state after creation . In this method, the basic application startup logic needs to be executed. This logic should only happen once in the entire life cycle of the Activity. . Among them, we can load layout layout resources, and also allow some network data to be requested here, because it is the first method, so try to initialize all the things that users need to see (usually resources) in this method , some time-consuming operations can be performed asynchronously.

  • onStart() The system calls this callback when
    the Activity enters the "started" state . This method call makes the activity visible to the user as the app prepares the activity to come to the foreground and support interaction. The application uses this method to initialize the code for the maintenance interface. For example, you need to reset the interface every time you enter the page, such as the refresh operation after entering the page. The refresh here means the data or interface refresh after re-entering the page.

  • onResume()
    The Activity comes to the foreground when it enters the "resumed" state , and the system calls this method callback. At this point, the application is visible and interactive to the user . The application will remain in this state until some event occurs that takes the focus away from the application. Such events include an incoming call, the user navigating to another activity, or the device screen turning off. Because this method will also be called when the interface returns, this method is a good choice when you want to refresh some data. Unlike the refresh in onStart(), onResume has an additional link from onPause to onResume (the link will be explained in the next paragraph).
    Also, under the requirements of some specific situations, such as face recognition requirements, sometimes we will actively call the onResume method on some interfaces with cameras, so that it will continue to execute to refresh the data in the camera stream we intercepted. At this time, the onResumed method will be called continuously to refresh the stream data we intercepted.

  • onPause()
    The system treats this method as the first sign that the user is about to leave your Activity (although this does not always mean that the Activity will be destroyed); this method indicates that the Activity is no longer in the foreground (although Activity is still visible when in modal), enters the "paused" state . In this method, you can first suspend some functions that do not need to run when you are not in the foreground to release some resources, such as sensors and cameras. Generally speaking, these tasks should not be too time-consuming. If the state is awakened by starting a new Activity, it will affect the display of the new Activity. The onPause of the current Activity must be executed before the onResume of the new Activity will be executed.

  • onStop()
    If the Activity is no longer visible to the user , it has entered the **"stopped" state**, so the system will call this method callback. This can happen, for example, when a newly started Activity covers the entire screen. The system can also call this method if the Activity has finished running and is about to be terminated. In this method, we can release or adjust resources that are not used when the application is not visible to the user, such as pausing animation effects, or switching from precise to coarse location updates. Relatively CPU-intensive shutdowns should also be performed using onStop(). For example, if you can't find a better time to save information to the database, you can do so during this method.

  • onDestory()
    If the Activity is about to end , onDestroy() is the last life cycle callback received by the Activity, indicating that the Activity is about to be destroyed by the system and enter the "destroyed" state . When the Activity is in the stopped state (onStop), it may enter the death state everywhere, because the system may forcibly end the Activity due to insufficient memory. Of course, we can also use finish() to actively destroy an Activity to execute it immediately. This method is ready to be destroyed . You can use this method to release some resources generated in Acitvity (such as Service, BroadReceiver, Map, etc.).

Other links in the life cycle

From the figure, we will find that the life cycle of Acitvity also has the possibility of other calling sequences. For this, I have learned from small to large spans one by one that these links may be triggered and experienced under what circumstances.

  1. From onPause to onResume
      , when the Activity has gone through this link, it also indicates that it has lost focus and restored focus. We can start from the situation of losing focus. It will be triggered when we click the multitasking key to enter the multi-window mode , because whenever, Only one app (window) can have focus, so all other apps are suspended. Or there is a new semi-transparent Activity (such as a dialog box) overlaid on top of the Activity. As long as the Activity is still partially visible, the focus will be lost, and this method will also be triggered when returning to the original page to make the Activity regain focus.
  2. onStop onRestart to onStart
    are generally called when the Acitvity is not visible and the return page is visible , but Zhongjian will go through another onRestart method to tell you that the Activity is returned, like this link is jumping to other pages, or entering the background It will be triggered when it returns later.
    For example, if the user presses the Home button to switch to the desktop or opens a new Activity, then the current Activity will be paused, that is, onPause and onStop are called, and then the user returns to this Activity, and this will happen.
  3. From onStop to onCreate
    , when the state of the Activity is ejected from the memory, the process where the Activity is located is terminated to release the memory, such as returning to the page after a long time in the background or switching between horizontal and vertical screens . At this time, the entire application process will be released. Of course, this It does not mean that this process does not exist, its application logo and activity stack will be in the background to be restored. It should be noted that it is not only the Activity that is killed here, but the entire application process, which will clear any interface state stored in the Activity instance. So if we need to consider saving and restoring the instantaneous interface state when the user returns to the page , regarding this behavior, I also call it the abnormal life cycle in the habit of other bloggers .

Activity exception life cycle

When the process where the Activity is located is terminated, such as when the horizontal and vertical screens are switched in the page, and we need to restore the previous page content and data when the user re-enters the page, we can use onSaveInstanceState and onRestoreInstanceState in the exception life cycle. recover. Among them, onSaveInstanceState can save the state information to the instance state Bundle . The default implementation of this method saves transient information about the state of the Activity's view hierarchy, such as the text in an EditText or the scroll position of a ListView. We can store the instantaneous information that needs to be stored in the Bundle before the Activity is completely destroyed by rewriting the parent class method, and then after the Activity is recreated, the previously stored value can be restored through the Bundle in OnCreate or onRestoreInstanceState Get and restore , where the Bundle in OnCreate and onRestoreInstanceState is no different.

Because the Activity may be killed, the variables used in the thread and some interface elements will be recycled, so you can consider using Android's message mechanism (Handler) to deal with multi-threading and interface interaction issues.

It should be noted that the abnormal life cycle will only be triggered when the process where the Activity is located is terminated, otherwise the onSaveInstanceState and onRestoreInstanceState methods cannot be called in general.

insert image description here

Activity life cycle test code

The following code can be copied to verify and print the life cycle, and practice will yield true knowledge.

public class MainActivity extends AppCompatActivity {
    
    
 
    /**
     * Activity创建时被调用
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e("onCreate");
    }
 
    /**
     * Activity被异常终止后 在onStop方法前被调用
     * @param outState
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    
    
        super.onSaveInstanceState(outState);
        Log.e("onSaveInstanceState is invoke!!!");
    }
 
    /**
     * Activity被异常终止后 在onCreate方法后被调用
     * @param savedInstanceState
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    
    
        super.onRestoreInstanceState(savedInstanceState);
        Log.e("onRestoreInstanceState is invoke!!!");
    }
 
    /**
     * Activity从后台重新回到前台时被调用
     */
    @Override
    protected void onRestart() {
    
    
        super.onRestart();
        Log.e("onRestart is invoke!!!");
    }
 
    /**
     *Activity创建或者从后台重新回到前台时被调用
     */
    @Override
    protected void onStart() {
    
    
        super.onStart();
        Log.e("onStart is invoke!!!");
    }
 
 
    /**
     *Activity创建或者从被覆盖、后台重新回到前台时被调用
     */
    @Override
    protected void onResume() {
    
    
        super.onResume();
        Log.e("onResume is invoke!!!");
    }
 
    /**
     *  Activity被覆盖到下面或者锁屏时被调用
      */
    @Override
    protected void onPause() {
    
    
        super.onPause();
        Log.e("onPause is invoke!!!");
    }
 
    /**
     *退出当前Activity或者跳转到新Activity时被调用
     */
    @Override
    protected void onStop() {
    
    
        super.onStop();
        Log.e("onStop is invoke!!!");
    }
 
    /**
     *退出当前Activity前被调用,调用之后Activity就结束了
     */
    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        Log.e("onDestroy is invoke!!!");
    }
}

tips

1. How can the horizontal and vertical screens not rebuild the life cycle?
As mentioned in the article just now, if the dynamic horizontal and vertical screen switching in the page will trigger the destruction and restart of the life cycle, which is the trigger process of the abnormal life cycle, but starting from Android 3.2 (API Level 13), Google officially considers the horizontal and vertical screen With the increasing number of usage scenarios, we can avoid this situation by adding screenSize to the configuration item of Activity, that is, configChanges = orientation|screenSize. Configure as follows:

	<activity
   	 	android:name="com.ftd.activity.ActivityXXX"
    	android:configChanges="orientation|keyboardHidden|screenSize"/>

Taking Api13 as the dividing point, the processing is as follows:

  • If the Activity configChanges attribute is not manually configured, the system will destroy and rebuild the Activity by default.
  • Below API13, the Activity configChanges attribute contains orientation to prevent the Activity from being destroyed and rebuilt.
  • For API13 and above, the Activity configChanges attribute contains both orientation and screenSize to prevent the Activity from being destroyed and rebuilt.

2. What does the visibility of onStart() mean?
I just mentioned that the call to onStart() means that it is visible to the user. It should be noted that the visible to the user does not mean that the interface is visible. It means that the Activity is visible to the user. The Activity is created and known to the user, but it is not in the foreground. , the interface has not been drawn yet , so it cannot be interacted with. It can also mean that the process it is in is a visible process .
From onStart to onResume, the Activity is created and the layout is loaded, but the interface has not been drawn yet, but the interface will be displayed through the handleResumeActivity method after the onResume method is executed. The following is the handleResumeActivity() method called during the startup of the Activity. In this method, the onResume method and the addView method are called to complete the first drawing of the View and display it on the interface

	@Override
    public void handleResumeActivity() {
    
    
        //onResume 
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        //addView 将view添加和显示
        if (r.window == null && !a.mFinished && willBeVisible) {
    
    
            wm.addView(decor, l);
        }
    }

Possible related problems

For the answers to the questions, please refer to the answers below, or make appropriate expansions based on the answers below in this article

1. Do you understand the life cycle? Please describe the life cycle of Activity?
These two questions, we can start from these angles to explain, what is the life cycle, what is its function, and what are the specific methods implemented in its life cycle, and what are these methods used for?
Answer:
  The life cycle is the various states that the Activity goes through from the beginning to the end. The various states experienced from start to finish. The transition from one state to another, from the initial startup to running and finally being shut down, the states experienced in such a process are called life cycles. (Here is an explanation of what a life cycle is. Of course, all life cycles are actually state changes, which can be used for general explanations.) Through the callback
  method of the Activity life cycle, we can know the process of each stage of the Activity, which lets us know that the Activity is executing The state at the time, and we can do the corresponding things during the execution of these state methods. (The role of the life cycle is explained here)
  The life cycle of the Activity often goes through the following methods:
    onCreate : At this time, it enters the "created" state. In this method, some initialization work can be done (loading layout resources, initializing Activity data, etc.).
    onStart : At this time, it enters the "started" state, indicating that the Activity at this time is visible to the user and is about to start.
    onResume : At this time, it enters the "resumed" state, indicating that the Activity has been created and can start activities. At this time, the user can already see the interface. At this time, the application is visible and interactive to the user . (After completing the cycle, you can respond to user interaction events).
    onPause: Enter the "paused" state at this time, indicating that the Activity is being paused. Under normal circumstances, onStop will be called next. In special cases, if the user quickly returns to the current Activity at this time, onResume will be called (extreme case).
    onStop : Enter the "stopped" state at this time, indicating that the Activity is no longer in the foreground , and you can do some heavyweight recycling work, and it should not be too time-consuming.
    onDestroy : Enter the "destroyed" state at this time, which is the last callback of the Activity life cycle, and we can do some recycling work and final resource release.

2. When two Activities are in the same process (application), and Activity A starts Activity B and returns. The order of life cycle methods of two activities?
It should be noted that only after the onPause method of Activity A is executed, Activity B will start to create accordingly. After the creation is completed and Activity A is no longer displayed on the screen, the onStop() method will be executed successively. If Activity B is transparent dialog theme Activity will not execute.

Here's the sequence of actions that occur when Activity A starts Activity B:

  1. Activity A's onPause() method executes.
  2. Activity B's onCreate(), onStart(), and onResume() methods execute in sequence (Activity B now has user focus).
  3. Then, if Activity A is no longer visible on the screen, its onStop() method executes.
  4. Activity B executes the return operation and enters the onPause() method at the same time.
  5. After returning, Activity A executes onReStart(), onStart() and onResume() methods
  6. Because the return itself is to remove this Activity from the stack, Activity B will then execute the onStop() and onDestory() methods
    insert image description here

Interview Skills Leading Questions

Through appropriate extended questions, not only can you properly expand your understanding of the question, but you can also bring your own rhythm into the interview, guide the interviewer's next questioning route, and try to bias the question to the field you are good at . This is just a reminder, the actual situation is different, but I also hope to provide you with some ideas for answering.
For the first question above, we can extend the visible in onStart combined with the small knowledge examples in this article to the visible process. On the one hand, it can show that your foundation is relatively solid, and on the other hand, it can induce the interviewer to further ask questions about the process. . Or expand the knowledge of the exception life cycle, and at the same time mention that the handler can be used to handle multi-threading and interface interaction issues to guide multi-threading related issues and so on.

Guess you like

Origin blog.csdn.net/number_cmd9/article/details/123412642
Recommended