To understand Handler, you need to understand Android’s Message mechanism.

Here, take users sliding wechat moments as an example to explain how the Message mechanism of Android works, and what each core component of the Message mechanism does

The Message to produce

The user swipes the screen, generating a series of input events (one Down event, several Move events, and one Up event), which are wrapped by the system as a series of messages (one Down Message, several Move Messages, An Up Message)

Message is used to convey information, and the above Message contains information about these input events, such as x and Y coordinates.

MessageQueue for Message

Once messages are generated, one of the questions is how do they get sent to the application? If I want to slide the circle of friends, these messages will be sent to wechat for processing. Wechat will send these events to the List control of the circle of friends, so that the List can generate new content and slide up and down.

The first thing I think of is whether I can directly send these messages to the List control of friends (SystemServer can Binder to the List control directly). It is possible, but it is troublesome. < span style = “max-width: 100%; clear: both; min-width: 100%; Does each control send a duplicate Message? That’s obviously not what we want.

SystemServer can’t send it directly to controls, so can’t send it directly to applications and let applications handle it themselves? The answer is yes, and Android does the same thing now. If your application prepares a MessageQueue (Message queue) and I have a Message, I put it in the MessageQueue, and your application processes it itself, isn’t that beautiful? That’s where MessageQueue comes in

Which sent the Message

After the application prepares a MessageQueue, SystemServer wraps a series of Input messages (a series of Down messages, several Move messages, An Up Message) was put into wechat MessageQueue, and wechat was left to read the contents of MessageQueue and update the UI itself

The problem is that a MessageQueue is just a Message store and someone has to manage the MessageQueue. For example, there are several messages in MessageQueue. Who should handle these messages?

Looper is introduced here, and Looper decides who should send the Message to be processed. Looper will retrieve the Message one by one in the order in which the Message is stored in the MessageQueue. According to the information contained in Message (who do I want to be processed by – target), send it to the corresponding person for processing

In this example, the Message targets are the main thread handlers of wechat

Handler to handle the Message

Looper sends the Message to the appropriate person for processing. This person is Handler. Looper sends the Message to the appropriate person for processing. As the last link in the Message mechanism, the Handler reads the contents of a Message and performs related processing according to the contents.

In this example, a series of Input messages will eventually be processed by the main thread Handler of wechat and passed to the corresponding List control through the complex process of event transmission and event distribution. The List control will follow the contents of the Input Message. Calculate the position of each Item in the next frame and update the Item and its contents, so as to produce the sliding effect of List and complete the sliding process of moments

Message Mechanism summary

With the Message mechanism example above, it makes sense to understand the following diagram, as shown in the titles above

  1. Message Carries content
  2. MessageQueue for Message
  3. Which sent the Message
  4. Handler to handle the Message

App, the main thread

So, what about the main thread of your App? Here is the logic to invoke activityThread. main after the App process is created

frameworks/base/core/java/android/app/ActivityThread.java public static void main(String[] args) { ...... PrepareMainLooper (); // Create Looper, Handler, MessageQueue Looper. PrepareMainLooper (); . ActivityThread thread = new ActivityThread(); thread.attach(false, startSeq); If (sMainThreadHandler == null) {sMainThreadHandler = thread.gethandler (); }... // Start preparing to receive messages looper.loop (); }} / / to the main thread of stars frameworks/base/core/Java/android/OS/stars. Java public static void prepareMainLooper () { prepare(false); synchronized (Looper.class) { if (sMainLooper ! = null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); }} / / prepare method creates an object which frameworks/base/core/Java/android/OS/stars. Java private static void prepare (Boolean quitAllowed) { if (sThreadLocal.get() ! = null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); } // when the Looper object is created, At the same time create a MessageQueue frameworks/base/core/Java/android/OS/stars. Java private stars (Boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }Copy the code

The Looper and MessageQueue of the main thread have been created through the above process, which lays the foundation of the Message mechanism. If a Message comes in later, the MessageQueue of the main thread will enter. Looper then sends it to the corresponding Handler

For the main thread, this Handler is inside the ActivityThread, so let’s just grab a little snippet of the Handler method. If you’re familiar with the code, BIND_APPLICATION is the section that you often see in Systrace when a new process starts

frameworks/base/core/java/android/app/ActivityThread.java class H extends Handler { public static final int BIND_APPLICATION = 110; public static final int EXIT_APPLICATION = 111; public static final int RECEIVER = 113; public static final int CREATE_SERVICE = 114; public static final int SERVICE_ARGS = 115; public static final int STOP_SERVICE = 116; public void handleMessage(Message msg) { switch (msg.what) { case BIND_APPLICATION: Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication"); AppBindData data = (AppBindData)msg.obj; handleBindApplication(data); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); break; }}}Copy the code

So, before you asked, is ActivityThread the main thread? Why didn’t Thread inherit? An ActivityThread is not a Thread. Instead, it has a Handler called H that handles messages from the main Thread. The life cycle of an Activity, a Service, and a BroadcastReceiver are all handled in the mainline of the ActivityThread (H) Handler.

Interthread communication

After the main thread of the App is initialized, the Message mechanism is running. What about the child threads? Child threads also have a Message mechanism, with their own MessageQueue, Looper, and Handler.

When Looper sends a Message, it will send it to the corresponding Handler according to the Message’s own wishes (target Handler). This Handler can be a child thread Handler, a main thread Handler, or any other Handler in the App process, as long as you know and specify this Handler

A very typical example is AsyncTask. If you create an AsyncTask on the main thread, then the AsyncTask will send a Message to the Handler of the main thread to update the UI of the main thread after the child thread completes the time-consuming task

Can a child thread update the UI

Since the main thread and the child thread are Message mechanisms, can the child thread update the UI at all? The answer is yes, but there may be some problems. For example, when the main thread is executing doFrame and the Measure method has just finished, the child thread changes the width and height of the View. Then, when the main thread is executing Layout, the position of the View may be wrong. If you are interested, you can remove the checkThread restriction code and update the UI in the child thread.

Android uses checkThread() to ensure that only the main thread can update the UI

    void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }
Copy the code

The last

About how to learn Android Framework development knowledge, recently fortunately in the hands of the former Technical director of Ali picked up the Android Framework advanced development notes, today to share with you.

This note explains the main modules of the Framework, from the deployment of the environment to the application of technology, and then to the actual project, so that we can not only learn the use of the Framework technology, but also learn how to use the Framework to solve the actual problem, from simple to deep, detailed analysis of the Framework, so that you can simply and efficiently learn this knowledge!

If there is a need to obtain the complete information of the document can be friends【 Click on me 】Get it free.

Chapter 1: In-depth analysis of Binder

Binder mechanisms as a means of interprocess communication permeate almost all of the Andorid framework layer. The basic communication mechanism of Android Binder must be understood first. Binder mechanisms as a means of interprocess communication permeate almost all of the Andorid framework layer. The basic communication mechanism of Android Binder must be understood first.

Knowledge in this chapter

  • Binder series – Introduction
  • Binder Driver a preliminary
  • Binder Driver revisited
  • Binder start ServiceManager
  • Get ServiceManager
  • Registration Service (addService)
  • GetService (getService)
  • The Framework layer analysis
  • How to use Binder
  • How do I use AIDL
  • Binder to summarize
  • Binder interview questions

Chapter 2: Parsing Handler in depth

This chapter first macro theoretical analysis and Message source code analysis, and then to MessageQueue source code analysis, Looper source code analysis, handler source code analysis, handler mechanism implementation principle summary. Finally, we also sorted out and handled all the interview questions.

Handler is a long, step-by-step chapter that I’m sure won’t disappoint you if you stick with it.

Knowledge in this chapter

  • Macro theoretical analysis and Message source code analysis
  • MessageQueue source code analysis
  • Looper source code analysis
  • Handler source code analysis
  • Summary of the implementation principles of the Handler mechanism
  • Handler interview question all parse

Chapter 3: Dalvik VM process system

Andorid system startup, init process, Zygote, SystemServer startup process, application creation and use, Activity creation, destruction Handler and Looper.

Chapter 4 analyzes WMS in depth

Window management frame system animation frame View working principle.

The fifth chapter PackagerManagerService

Package management services, resource management related classes.

If there is a need to obtain the complete information of the document can be friends【 Click on me 】Get it free.