Detailed summary of the source code implementation of the Activity startup process of the four major components of Android

   Detailed summary of the source code implementation of the Activity startup process of the four major components of Android


Detailed explanation of the source code implementation of the four major components of Android series blog directory:

The Android application process creation process
reveals the secret of the bindService source code implementation details of the four major components of Android. Detailed description
of the activity startup process source code implementation details of the four major components of Android. Summary The implementation details
of the activity start process source code of the four major components of Android (1)


Preface

  I have been planning to write a series of blogs on the detailed explanation of the activity startup process, but I have always felt that my skills are not enough, not because I am not confident enough, it is really because there is a reason! The startup of Activity involves a lot of logic, and its startup process is more complicated. It involves the creation of Android processes, the scheduling of the life cycle in the Activity, the selection and scheduling of the Task stack, and the Android Process communication Binder IPC mechanism and other aspects of knowledge points! For these series of blogs, I have been preparing for a long time, and have laid the foundation for the key knowledge to be involved in advance:

Although I have prepared so much for the above, I am still very worried about writing this series of blogs. I am not worried about my lack of skills and fear of omissions or errors in what I write, but I still bite the bullet. Got it! At least, I am writing with my heart! Of course, it would be the happiest if I could help the guys!

  • Note : The introduction in this article is based on the Android 7.xx platform, and the code paths involved are as follows:
frameworks/base/services/core/java/com/android/server/am/
  --- ActivityManagerService.java
  --- ProcessRecord.java
  --- ActivityRecord.java
  --- ActivityResult.java
  --- ActivityStack.java
  --- ActivityStackSupervisor.java
  --- ActivityStarter.java
  --- TaskRecord.java 

frameworks/base/services/core/java/com/android/server/pm、
 --- PackageManagerService.java

frameworks/base/core/java/android/app/
  --- IActivityManager.java
  --- ActivityManagerNative.java (内部包含AMP)
  --- ActivityManager.java
  --- AppGlobals.java
  --- Activity.java
  --- ActivityThread.java(内含AT)
  --- LoadedApk.java  
  --- AppGlobals.java
  --- Application.java
  --- Instrumentation.java
  
  --- IApplicationThread.java
  --- ApplicationThreadNative.java (内部包含ATP)
  --- ActivityThread.java (内含ApplicationThread)
  --- ContextImpl.java
  • And in the subsequent source code analysis process, for the convenience of brief description, the following brief description will be made:
    ApplicationThreadProxy is abbreviated as ATP
    ActivityManagerProxy and abbreviated as AMP
    ActivityManagerService is abbreviated as AMS
    ActivityManagerNative is abbreviated as AMN
    ApplicationThreadNative is abbreviated as ATN
    PackageManagerService is abbreviated as PKMS
    ApplicationThread is abbreviated as AT
    ActivityStarter is abbreviated as AS , Don’t confuse
    ActivityServices here. ActivityStackSupervisor is referred to as ASS


1. The overall summary and preliminary knowledge preparation of Activity startup

  While writing this series of blogs, I accidentally saw an article on WeChat ID. Why do I hate you to talk about code line by line? , The last paragraph is very reasonable!

  Every time, I see such a technical article is very painful. What do you mean by telling me line by line of code? Can't I understand C language? Can you tell me something about what you want to write first? What is the overall framework of what you write? As for the code, can you give me some key points, function names, or flowcharts, can I do it myself?
  Why are articles on running accounts generally not helpful to readers? Because it really gets twice the result with half the effort. It took me a long time to read you, but after reading it, I still don’t understand, because it’s all details, because I didn’t form the overall outline.

Yes, this kind of blog looks at writing a lot of things, but readers feel that they have everything, but there is nothing! Therefore, in this series of blogs, we will abandon line-by-line analysis of the code, focusing on the key context. If readers are interested in the details, they can clarify the overall knowledge and then slowly deepen them. Follow the reading to thin the book first. The thickening theory diverges!


1.1 Overall summary of Activity startup

  Before officially starting the analysis of the long and complex startup process of Activity, let us first summarize the overall startup process of Activity (take cold start as an example), which can be roughly divided into the following stages:

  • The source end process sends a request to start the target Activity : 1. The Source end initiates a display/implicit start request to start the Activity

  • system_server process started by AMS process requests Activity : 2 . Intent to start parsing the target Activity 3 Creating target Activity corresponding ActivityRecord 4 . Find / Activity assigned to target or to create optimal Task stack 5 .Pause foreground Activity 6 .Resume request target Activity 7. AMS requests the zygote process to create a process for the target Activity





  • The zygote process processes the request phase of creating the target Activity process sent by the system_server process : 8. zygote accepts the AMS request to fork to create the process to which the target Activity belongs . 9. Calls RuntimeInit to initialize the target process operating environment . 10. Calls the target process ActivityThread main thread main method through reflection to start A new era of goal progress


  • The start phase of the target Activity process : 11. Open the Looper message loop of the target Activity process . 12. Register the ApplicationThread to the system_server process . 13. Create the target process Application and execute its onCreate method.


  • Open the target Activity life cycle stage : 14. Really start the target Activity 15. Load the target Activity through reflection 16. Execute the target Activity life cycle 17. Initialize the target Activity window to prepare for display



  • Target Activity display stage : 18. New DecorView 19. New ViewRootImpl 20. Add window to WMS ready to display


  • Ending work on Source side Activity : 21. Source side Activity executes logic such as onStop()

In the next series of blogs, we will start with the above outline and expand the explanation of the Activity startup process through pseudo-code combined with analysis of key methods or functions! The leading guys can have a clear understanding of the activity startup process as a whole. As for the various small details involved, it is up to you guys to do it yourself!



2. Preliminary knowledge preparation for Activity startup

  Although we have stored some knowledge for the startup of Activity, it is still far from enough. Many concepts involved in the startup process of Activity need to be familiar and familiar in advance.

2.1 Activity cold start and hot start

  I think guys often see some blogs mentioning the hot and cold start of Activity, but some guys may be the first to hear this concept. The hot and cold start here can be different from the hot and cold start during driving. A brief description of the two methods of hot and cold startup in Activity in Android:

2.1.1 Activity cold start

  When the Activity is started, there is no process of the application corresponding to the Activity in the background. At this time, the Android system will create a corresponding process for the Activity, and then execute the process of Activity creation and display. This startup method is cold start. Its main feature is the cold start. Because the system will create a new process to assign to it through zygote, it will first create and initialize the Application class, and then create and initialize the target Activity class (including a series of measurement, layout, and drawing). Finally displayed on the interface.

2.1.2 Activity hot start

  When the target activity is started, the Android background has the corresponding application process of the activity (for example: press the back key, home key, although the application will exit, but the application process will still remain in the background, you can enter the task list to view) , So in the case of an existing process, this startup will start the application from the existing process. This method is called a hot start. The biggest feature of this startup method is that an App application will only be initialized once from the creation of a new process to the destruction of the process, so there is no need to create and initialize the Application, and go directly to the creation and display of the target Activity (including a series of measurements, layouts, draw).


2.2 Activity life cycle

  I think this is a knowledge point that many guys must have when they first started Android, that is, the life cycle of Activity, which is as follows:

  • protected void onCreate(Bundle savedInstanceState)
  • protected void onRestart(…)
  • protected void onStart(…)
  • protected void onResume(…)
  • protected void onPause(…)
  • protected void onStop(…)
  • protected void onDestory(…)

The above are the callback methods for each period in the Activity life cycle. In different methods, we can execute different logic. The classic diagram is as follows:

Insert picture description here


2.3 Activity display start and implicit start

  As we all know, the startup mode of Android components has two explicit calls and implicit calls. These two calling methods are well understood from the literal meaning. Let us explain separately.

2.3.1 Display startup

  Explicit calls need to specify the components to be started, such as:

Intent intent = new Intent();
intent.setClass(this,XXXActivity.class);
startActivity(intent);

Here you can see that display startup is to directly reference the bytecode of the Activity that needs to be started when the Intent object is initialized. The advantage of display startup is that it can directly tell the Activity object started by the Intent object without executing the intent filter index which Activity needs to be started. Many blogs on the Internet say that it shows that it is impossible to start Activity objects of other processes because the bytecodes of the Activity objects of other processes cannot be obtained. I think this statement is incorrect. For example, as shown below, this is not obvious cross-process startup. Is the Activity of the end process?

 Intent intent=new Intent();
 ComponentName cName = new ComponentName("com.android.settings","com.android.settings.Settings$WifiSettingsActivity");
 intent.setComponent(cName);
 startActivity(intent);

2.3.2 Implicit start

  The implicit call does not need to specify the component to be started, but matches through Action, such as:

        Intent intent = new Intent();
        intent.setAction("xxx.xxx.xxx");
        startActivity(intent);

Here we can see that the implicit start is used to start the activity with the intent-filte configuration of the Action by configuring the Action. Usually, the implicit start is used for the start of components that do not know the specific information of the component but know the external action.


2.4 Activity start mode

  This knowledge point is also commonly used by examiners during interviews, and it is also a point that we often use more in actual combat. When the Activity is defined in the \AndroidManifest file, you can specify how the activity should be associated with the task through the launchMode attribute of the element. The values ​​are as follows:

  • standard (default startup mode)
  • singleTop
  • singleTask
  • singleInstance

Different startup modes will execute different logic when starting the Activity. The system will store the Activity in different Activity stacks according to different startup modes. For detailed introduction of the above four modes, please refer to the Google documentation for tasks and return stacks .


2.5 Analysis of ActivityManagerService Class Diagram

  ActivityManagerService is a Java layer Binder service provided by Android that is responsible for the startup, switching, scheduling of the four major components of the system, and the management and scheduling of application processes, but its code is cumbersome and lengthy. If you don’t familiarize yourself with it in advance, then the analysis will follow Will be dizzy. Let's first look at its class diagram implementation, as follows:
Insert picture description here

Here is a brief introduction to the class functions involved:

  • The Binder server of ActivityManagerService
    Activity management mechanism belongs to a system service. Used to manage various behaviors of Activity, control the life cycle of Activity, dispatch message events, low memory management, etc. Implemented the IBinder interface, which can be used for inter-process communication

  • ActivityManagerProxy
    AMS service proxy, third-party applications use this class to implement remote RPC requests to AMS

  • ActivityStarter
    AMS has to deal with too many things. So the ActivityStarter was created to handle the Intent and Flags of the Activity, as well as the related Stack and TaskRecord.

  • ActivityStack
    order to work together for many Activity without becoming confused, Android platform, designed a stack mechanism for managing Activity, its compliance with the principles of the advanced cycle out, the system is always displayed at the top has Activity

  • ActivityStackSupervisor
    is responsible for the management of all Activity stacks. Three Activity stacks, mHomeStack, mFocusedStack and mLastFocusedStack are managed internally. Among them, mHomeStack manages the Activity stack related to Launcher; mFocusedStack manages the Activity stack currently displayed in the foreground Activity; mLastFocusedStack manages the Activity stack that was last displayed in the foreground Activity


2.6 Analysis of ApplicationThread Class Diagram

  After AMS creates the target process with the help of the zygote process, it needs to use an intermediary to complete the control of the target process components. This is our turn to the ApplicationThread. It is through it that AMS completes the management and scheduling of the four major components of the target process. , Let us look at its class diagram:

Insert picture description here
Here is a brief introduction to the class functions involved:

  • ApplicationThread
    can see that it is a Binder entity object, which is mainly responsible for communicating with AMS and receiving various RPC commands from AMS, and then completing the management and control of the four major components. ApplicationThreadProxy ApplicationThread service agent. Third parties usually use it to complete ApplicationThread Remote call

  • There is an entrance to the main thread of the process in ActivityThread,
    which is similar to the function of main. It is responsible for establishing the Looper cycle and assisting the four major components of AMS and the various scheduling of the life cycle.

2.7 Introduction to ActivityRecord, TaskRecord, ActivityStack

  Several very important data structures are involved in the start of Activity, that is, ActivityRecord, TaskRecord, ActivityStack and ProcessRecord. The relationship between these data structures can be represented by the following class diagram relationship:
Insert picture description here
here we only need to There is a summary of the above class diagrams. As for how they are connected in series, I will not show it for the time being. It will be mentioned in the subsequent source code. Let's briefly introduce them individually:

  • ProcessRecord
    This data structure corresponds to our App process, which corresponds to one or more ActivityRecord (of course, there may be other four major components such as Service)
  • ActivityRecord
    , as the name suggests, this data structure corresponds to our Activiyt, stores the related information of Activiyt, and each ActivityRecord corresponds to a TaskRecord, the member task of the type TaskRecord in ActivityRecord, the task to which the record belongs, there is one thing to note here It is that Activity and ActivityRecord are not one-to-one, but one-to-many, because an Actitiy may have multiple startup methods, resulting in multiple ActivityRecords
  • TaskRecord
    A TaskRecord is composed of one or more ActivityRecords, which is the task stack we often say, with the characteristics of last in, first out
  • ActivityStack is
    used to manage TaskRecord, it has a member mTaskHistory of type ArrayList, used to store TaskRecord
  • ActivityStackSupervisor
    is responsible for the management of all Activity stacks. Three Activity stacks, mHomeStack, mFocusedStack and mLastFocusedStack are managed internally. Among them, mHomeStack manages the Activity stack related to Launcher; mFocusedStack manages the Activity stack currently displayed in the foreground Activity; mLastFocusedStack manages the Activity stack that was last displayed in the foreground Activity

Well, I won't go into depth here, let the guys have a basic concept. Regarding the above-mentioned knowledge points, the blog ActivityRecord, TaskRecord, ActivityStack, and Activity start mode are highly recommended . You deserve it!



summary

  Unexpectedly, I have written so much for the preliminary knowledge of Activity startup. For the convenience of reading for the guys and the beautiful and detailed explanation of the layout, I will come here first. If you want to really understand the source code level of Acitivity startup, you must do it. Prepare well, otherwise you will become more and more confused and helpless in reading, and you may give up as you read, because you will find that it is so difficult. There is one knowledge point on the left and one knowledge point. Don't ask me why I said that, because I came here too, and I was confused and helpless and thought about this in my heart! So guys must be mentally prepared and must not give up halfway! In the next chapter, we are about to officially start to enter the actual combat analysis, I hope you guys can continue to pay attention. For the detailed decomposition of Activity startup , please refer to the detailed explanation of the source code implementation of the Activity startup process of the four major components of Android (1) .

Guess you like

Origin blog.csdn.net/tkwxty/article/details/108652250