This column focuses on sharing the knowledge of large-scale Bat interview, and it will be updated continuously in the future. If you like it, please click a follow

Interviewer: AMS in Android play what role, a simple analysis of the Android source code

Psychological analysis: This problem happens in most situations. Faced with this problem many job seekers are at a loss, do not know how to speak. AMS itself is complicated and difficult to understand. After years of work, it is difficult to understand the function of AMS. In fact, we can start from the following points: component startup, process switching, and Crash exception

Job seeker :AMS is difficult to express, we will start from the most familiar Activity, and gradually in-depth and analysis, with concentration to tell the interviewer, I have in-depth study. Next, we analyze the action and mechanism of AMS from five lines

An overview of the
Most of you have heard of ActivityManagerService (hereafter AMS) mentioned in this article.

AMS is the most core service in Android, mainly responsible for the startup, switching, scheduling of the four major components of the system, and the management and scheduling of application processes. Its responsibilities are similar to the process management and scheduling module in the operating system, so it is very important in Android. AMS is the first difficult bone we encounter [①], which involves many knowledge points. In order to help readers better understand AMS, we will take you to analyze it by five different lines.

  • First line: The AMS call trace in SystemServer is analyzed, just like any other service.
  • The second line: take am command to start an Activity as an example, analyze the creation of application process, the start of Activity, and the interaction between them and AMS.
  • The third line and the fourth line respectively analyze the processing flow of Broadcast and Service in AMS.
  • Fifth line: Taking a Crash application process as the starting point, analyze how AMS takes care of the aftermath of the application process. In addition to these five lines, it will also analyze the frequently appeared in these five lines and AMS application process scheduling, memory management and other related knowledge. The tips for ContentProviders will be covered in the next chapter, but this chapter will cover the basics of contentProviders. Let’s take a look at the AMS family map:

As can be seen from the figure:

  • AMS by ActivityManagerNative (hereafter referred to as “AMN) class derivation, and realize the Watchdog. Monitor and BatteryStatsImpl BatteryCallback interface. AMN, derived from Binder, implements the IActivityManager interface.
  • The client uses the ActivityManager class. Because AMS is a core service, many apis are not available to clients, so the designers did not add ActivityManager directly to the AMS family. Inside the ActivityManager class, call AMN’s getDefault function to get an ActivityManagerProxy object that communicates with AMS.

AMS is created by the ServerThread thread of SystemServer;

1. Overview of ActivityManagerService

The four key functions analyzed in this section are all complicated, and related knowledge points are summarized as follows:

  • The AMS main function: creates an AMS instance. The most important job is to create the Android runtime environment, and get an ActivityThread and a Context object.
  • AMS setSystemProcess function: This function registers services such as AMS and meminfo into the ServiceManager. In addition, it creates a ProcessRecord object for SystemServer. Since AMS is the process management and scheduling center of the Java world, it is necessary to treat Java processes equally, even though SystemServer is a system process, it has to be incorporated into AMS’s management scope.
  • AMS installSystemProviders: loads SettingsProvider for SystemServer.
  • AMS systemReady: Do the last cleanup before the system starts up. After this function is called, HomeActivity is presented to the user. The analysis of AMS call track is the first line for us to crack AMS, and we hope readers can read it repeatedly to truly understand the knowledge points involved, especially the knowledge related to Android operating environment and Context.

2. startActivity

To summarize the entire startup process of startActivity in detail,

  • Process [2.1 ~2.4]: Run in the caller’s process, such as the launcher process that starts the Activity from the desktop. The launcher process uses ActivityManagerProxy as its Binder Client. Enter the system_server process (AMS Server).
  • Process [2.5 ~2.18]: run in the system_server system process, the whole process is the most complex, core process, the following part of the steps:
  • Process [2.7] : resolveActivity() will be called, with the help of PackageManager to query all the activities that meet the requirements in the system, when there are multiple activities that meet the conditions will pop up the box for the user to choose;
  • Process [2.8] : Create an ActivityRecord object, check whether App switch is running, and then handle the activity in MpendingActivityLauncher.
  • Flow [2.9] : Find or create a new Task for the Activity and set flags;
  • Process [2.13] : If there is no Activity in the non-finishing state, it goes directly back to the desktop; Otherwise, startPausingLocked() suspends the activity when mResumedActivity is not empty; Then enter startSpecificActivityLocked ();
  • Flow [2.14] : When the target process already exists, it will directly enter the flow [2.17]; when the process does not exist, it will create the process and still enter the flow [2.17] after layer upon layer calls;
  • Process [2.17] : ATP(Binder Client) used by system_server process, through Binder, program next enter the target process.
  • Process [2.19 ~2.18]: Runs in the target process. The Binder threads in the process send H. launch_activity to the main thread through the Handler message mechanism, which eventually creates the target Activity through reflection and enters the onCreate() life cycle. Here’s another way to summarize it:


Startup process:
  1. Click the desktop App icon, and the Binder IPC sends the startActivity request to the system_server process.
  2. After receiving the request, the system_server process sends a request to the Zygote process to create the process.
  3. The Zygote process forks a new child, the App process.
  4. The App uses the Binder IPC to request attachApplication for the Sytem_server process.
  5. The System_server process sends a scheduleLaunchActivity request to the App process via binder IPC after a series of preparations.
  6. The binder threads of the App process send LAUNCH_ACTIVITY messages to the main thread through the handler upon receiving the request.
  7. After receiving the Message, the main thread creates the target Activity through the launch mechanism and calls methods such as activity.oncreate (). By this, the App was launched, begin to enter the Activity life cycle, after the onCreate/onStart/onResume method, after the UI rendering can see the main interface of the App.


StartActivity summary for the second half

StarActivity summary

So much for starting an Activity. This all the way down, I believe that readers and the author feel that this trip is not easy. A recap of the trip:

  • The starting point of the trip is am. Am is a very important application in Android, readers must master its use. We use the AM start command to initiate the target Activity.
  • Next, enter ActivityManagerService and ActivityStack, the two core classes. In the first stage, the main work is to find or create ActivityRecord and the corresponding TaskRecord according to the startup mode and the startup flag. The second phase of work deals with activities that start or switch.
  • Firstly, the process of AMS directly creating target process and running Activity is discussed, which involves the creation of target process and initialization of Android running environment in target process. Create target Activity and trigger onCreate, onStart, onResume and other important function calls in its life cycle.
  • AMS pauses the current Activity and then creates the target process and runs the Activity. This involves the interaction between two applications and AMS, which shows how difficult it is. As you read through this section, it’s important to distinguish between the two phases of your journey: finding the right ActivityRecord and TaskRecord; The other is to schedule related processes to switch activities. In the SDK document, the most detailed introduction is the system processing strategy in the first stage, such as the startup mode, the role of the startup flag, etc. The second phase of work is actually related to scheduling Android components. The SDK documentation only introduces the lifecycle aspects of a single Activity. To be honest, this journey skips a lot of logic. For two reasons, on the one hand, due to limited energy and space, and on the other hand, as a scheduling core class, the code and processing logic related to AMS is very complex, and the interaction logic with WMS also makes the complexity even more complicated. Furthermore, I personally feel that this part of the code is far from efficient, rigorous and beautiful, and even a little ugly (in the process of analyzing them, it is far from the carefree feeling of studying Audio and Surface). Here are a few points for further research:
  • Processing flow of various startup modes and startup flags.
  • How to handle the Activity when the Configuration changes, and how to save and restore the state in the Activity.
  • Transitions and related processing at various stages of the Activity lifecycle. Transformations and processing related to the Fragment lifecycle have been added since Android 2.3.

3. Summary of broadcast processing

4. StartService flowchart

5.1 Process Description In the startService process, start the service from a process perspective

  • Process A: refers to the Process in which the startService command is called, that is, the Process that starts the service. For example, click the icon of the desktop App. In this case, Process A is the Process in which the service is launched.
  • System_server process: System process, the core carrier of the Java Framework framework, runs a large number of system services, such as ApplicationThreadProxy (ATP), ActivityManagerService (AMS), These two services run in different threads of system_server process. As ATP and AMS are both based on IBinder interface, they are both binder threads. Binder threads are created and destroyed by binder drivers, and the maximum number of binder threads per process is 16.
  • Zygote processes are incubated from init processes to create the parent Java layer processes. All Java layer processes are incubated from Zygote processes.
  • Remote Service process: the process where the Remote Service resides. It is incubated by the Zygote process and used to run the Remote Service. The main thread is mainly responsible for the life cycle of activities/services and other components and UI-related operations are run in this thread. Binder threads are AT least two applicationThreads (AT) and ActivityManagerProxy (AMP), as well as other threads.

In the figure, there are three IPC communication modes: Binder, Socket and Handler, which are represented by three different colors. Generally speaking, the communication between threads in the same process uses the Handler message queue mechanism, the communication between different processes uses the binder mechanism, and the communication with Zygote process uses sockets.

Startup process:

  • Process A uses Binder IPC to initiate startService requests to system_server.
  • After receiving the request, the system_server process sends a request to the Zygote process to create the process.
  • The zygote process forks the Remote Service process.
  • The Remote Service process sends attachApplication requests to the Sytem_server process through the Binder IPC.
  • After receiving the request, the System_server process performs a series of preparations and sends the scheduleCreateService request to the Remote Service process through binder IPC.
  • The Binder thread of the Remote Service process sends a CREATE_SERVICE message to the main thread through a handler.
  • After receiving the Message, the main thread creates the target Service through the emission mechanism and calls back to the service.oncreate () method. At this point, the service is officially started. If the created service is a local service or the process to which the service belongs has been created, you can directly create the service without going through steps 2 and 3.


5. Process management in AMS

As mentioned above, the Android platform rarely touches on the concept of processes, instead having four clearly defined components. However, as a system or framework running in Linux user space, Android not only can not get rid of the process, but also to make full use of the process management mechanism and means provided by Linux OS to better serve itself. ActivityManagerService, the core service for component execution management in the Android platform, takes over the job. Currently, AMS manages processes in only two ways:

  • Adjust the scheduling priorities and policies of processes.
  • Adjust the OOM value of a process.
6. Summary of App Crash processing

Process for an application process to Crash.

Summary of a.

ActivityManagerService is one of the core services of the Framework layer. ActivityManagerService is a subclass of Binder and provides the following functions:

  • Unified scheduling of four components
  • Process management
  • Memory management
ActivityManagerService startup process

ActivityManagerService is started in the startBootstrapServices method of the SystemServer process. SystemServiceManager. StartService (ActivityManagerService. Lifecycle. Class) main functions: to create ActivityManagerService. Lifecycle object; Call the Lifecycle.onstart () method.

Four. One of the main functions of the four components of unified scheduling

ActivityManagerService’s main function is unified management activity, service, broadcast, the provider of the creating, running, shut down. We start acitivity in our applications, we turn acitiviy off, and so on, and ultimately ams is centrally managed. This process is very complicated and can not be explained clearly in a short time. I recommend Lao Luo’s blog to explain the startup process of four components:

Android application internal startActivity process (startActivity) source code analysis Android system in a new process to start the process of custom service (startService) principle analysis Process analysis of Android application registerReceiver Process Analysis of Android application sendBroadcast Component Content Provider brief introduction and learning plan

One of the main functions is memory management

We know that when all acitiviy in a process is closed, the empty process is not killed immediately. It does not kill until the system runs out of memory. ActivityManagerService does not manage memory. The Android memory management module in the Linux kernel manages memory in conjunction with the OOM process. The Android process will tell the OOM process the oOM_adj value of each application through Ams when it is running. This value ranges from -16 to 15. The lower the value, the more important it is and the less it will be killed. When low memory occurs, the Linux kernel memory management module will inform the OOm process to forcibly exit the process with a higher value according to the priority provided by AMs. Thus, Ams only serves as a memory management function that provides the oOM_adj value of the process. The real memory management is done by calling the OOM process. Let’s see how the memory is freed by calling the Activity’s Finish () method.

When we call finish() manually or press the back key to shut down the activity, we simply call AMS’s finishActivityLocked methods to set the finish state of the currently closed Acitiviy to True, and then call Finish Will go first to start a new acitiviy, when after the completion of the new acitiviy startup notification Ams will through the message mechanism, Ams acitiviy before call activityIdleInternalLocked method to shut down.

About me

For more information, you can click about me. I really hope to communicate with you and make progress together. Currently, I am a programmer.