Today’s recommendation is xiaomi MIUI system engineer YogiAi opened “from the source of Android” free column.

Here’s what the author wrote about the introduction to the column:

Look at Android from a source point of view, follow this column, and you’ll be able to explore the fun world of source code with me. I don’t have to say much about the importance of reading source code, we all understand. But you can imagine one day, with your understanding of AOSP source code, you will be excited to have your pocket phone running your own modified and compiled system 🙂

Here are nine current titles and introductions to Android from the Source Code perspective, which the author will continue to update (subscribe to the end of the article) :


1, Android SharedPreferences

SharedPreferences is the most commonly used data persistence method in Android. It works by reading and writing XML files under shared_prefs to access data. There are a lot of articles on the web about this, so I won’t go over them. I will briefly list the time sequence diagram I drew and some suggestions on how to use it. Finally, I will summarize the occurrence of ANR.

2, how to generate testamp.txt from the source

Localted. TXT is stored in /data/anr for android, and the framework will dump the current thread stack at the same time as the popup Dialog, so that developers can analyze the root cause of anR.

ANR is short for Application Not Responsing. In short, ANR is a built-in mechanism of Android system to prompt users that the Application interface does Not respond. It is a way to avoid the Application interface being stuck all the time and increase the user friendliness of the system.

There are many reasons for ANR, all of which are caused by interface update blocked by executing tasks in the main thread for too long. The main reasons are as follows:

  1. Broadcast Timeout: The foreground broadcast lasts for more than 10s, and the background broadcast lasts for more than 60s. (It should be noted that only serial broadcast has timeout mechanism, and parallel broadcast does not have timeout mechanism. That is to say, if the broadcast is dynamically registered, call sendBroadcast directly to trigger. If the next Message in the main thread Looper does not trigger the timeout mechanism, the system will never pop up a Message indicating that the user has timed out, even if the broadcast is foreground.)

  2. Service Timeout: The foreground Service star exceeds 20s and the background Service star exceeds 200s

  3. Provider Timeout: the content Provider publishes more than 10 seconds

  4. Input Timeout: Key touch events are distributed for more than 5s

ANR can be caused only if the task is executed on the main thread. What kind of task is executed mainly includes the following:

  1. It takes too long to perform a task, such as reading or storing a file, or obtaining a file on a network

  2. The thread is blocked for too long, or it simply deadlocks

  3. For example, there are 16 Binder threads in total, one Binder main thread is occupied, and the remaining 15 worker threads are occupied

  4. The CPU is hungry and the load value is too large. Although the code is normal, the task has not been executed in time

Back to the testament.txt file, what information does it contain to help developers find the root cause of ANR problems?

In this article, I’ll start with an example of a tracted. TXT log, and then trace the source code to explain how it was generated.

How to implement data change monitoring from the source layer ContentService

ContentService is the server of the ContentResolver. It runs on the System_server process and provides all applications with access to the ContentProvider data interface. ContentService also provide an interface to monitor data changes at the same time, this article will from the perspective of the source code to parse registerContentObserver and unregisterContentObserver process.

4. Look at various contexts from the source point of view

Context familiarity for application development should be second only to Activity and Service familiarity. Context, also known as Context scene, represents an encapsulation of various information in the current running scenario. For example, the four major components need to be called to work, and the Context can also be used to obtain Resource objects such as Resource, Display, Theme, AssetManager, and WallPaperManager.

5. Ams.startprocesslocked from a source view

As we all know, Android system is a mobile operating system based on the Linux kernel. Linux uses copy-on-write to fork processes, creating unique identifiers and other light operations. The concept of processes and threads differs in the Linux world only in resource ownership. Essentially, both kernel implementations use the same structure, task_struct, with their own PID, PPID.

In the upper-layer framework world of Android itself, the concept of process has been very vague after layer upon layer of encapsulation. Basic developers only need to be familiar with the functions and usage scenarios of four components such as Activity, BroadcastReceiver and Service to complete the development process. Combined with network access, data storage, UI drawing and other business logic can complete a very good application.

However, the study of Android process startup timing and implementation principle for advanced learning is still of great benefit, not only to learn the process of thread internal knowledge, but also to learn the design master encapsulation mystery. Android application processes are created by forking the Zygote process, so all application process PPids are Zygote PID. In addition to copying the Zygote instance to a virtual machine instance, the new process also gets a message loop, Binder’s process communication pool, and a Binder main thread.

In this article, I’ll break down the Android process creation process in detail.

6, from the source point of view Binder. LinkToDeath

Binder messaging is ubiquitous in Android, from running a new application to sending a common TIME PICK broadcast to registering a ContentObserver to listen for changes in SMS data. As “mortal men must die”, the system_server process will exist as long as the phone is turned on, but ordinary applications, no matter how high their priority, will be forced to Close when the system runs out of memory, the user manually kills the application process, or an unresolvable BUG occurs in the application. At this point, since the application as the process communication server is dead, there is no need to save the data saved by the corresponding client and corresponding server. Otherwise, if the phone is not shut down and system_server does not clean up dead processes during its lifetime, then the use of such a mobile system will cause memory leaks and system resources will be slowly exhausted until the user can detect the system stuttering.

As a result, Binder processes need a death callback mechanism that notifies clients to clean up after a communication server has died. Android has implemented a DeathRecipient mechanism, where the client simply implements the death callback binderDied and calls linkToDeath, which will be called when the server dies.

7, from the source view of CPU related logs

On Android, common developers often encounter ANR(Application Not Responding) problems, where the Application main thread does Not respond. The underlying reason is that the Android framework is designed to put uI-specific, perceptive operations into a special thread, the main thread. Once the thread does not complete a task within a specified period of time, such as broadcasting onReceive, an Activity jump, or bindApplication, the framework generates what is known as an ANR, which pops up a dialog and gives the user the option to continue waiting or kill the application process that does not complete the task.

It is often said that developers perform time-consuming operations in the main thread, resulting in a task that takes too long to execute. Such problems are usually easy to locate and solve, and the root cause of ANR is often revealed by clicking bugreport.

Today we are talking about another common situation, which is often due to the backward CPU hardware equipment, the underlying CPU control strategy caused by improper. This is an annoying problem that normally would never take time because it can also have ANR and stutter, making the user experience extremely bad.

8. Look at broadcasting from the source point of view

Almost every Android app inevitably uses radio. For example, monitoring the status of WIFI, obtaining time, and even the most commonly used alarm clock functions are realized by combining AlarmManager and broadcast. Understanding the source code of the broadcast registration, sending and receiving implementation will enable us to better understand the Android system. At the same time, based on our understanding of the broadcast, we can also quickly grasp the implementation principle of other components in AMS.

9. Look at the Activity lifecycle from a source code perspective

Activity is a must-learn for almost any starting Android programmer. We all know that android’s biggest feature is its ability to present a user interface that allows users to interact with applications, and the most important basic classes are activities. However, many Android developers assume they understand Activity life cycles and launchMode and so on. In fact, however, there is a very complex logic underlying the Android source code to support changes in the Activity lifecycle.

This column is free, if you feel good, I hope you can forward this article. Follow the mini-column platform and reply “Android from a source perspective” or reply “Source” to get a subscription to this column.