current position:Home>Android handler source code analysis 2

Android handler source code analysis 2

2022-01-27 03:44:45 Sniper 000

This is my participation 8 The fourth of the yuegengwen challenge 17 God , Check out the activity details :8 Yuegengwen challenge

stay ActivityThread Of main Method , This method is the entrance to the application . main The source code of the method is as follows :

public static void main(String[] args) {

    // Code ellipsis 


    ActivityThread thread = new ActivityThread();

    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();

    if (false) {
                LogPrinter(Log.DEBUG, "ActivityThread"));

    // End of event ActivityThreadMain.

    throw new RuntimeException("Main thread loop unexpectedly exited");
 Copy code 

eureka Looper.prepareMainLooper(), This sum Looper.prepare() It's so similar , Follow in and have a look

public static void prepareMainLooper() {
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        sMainLooper = myLooper();

 Copy code 

Back again , Still called prepare Methodical . So the main thread has created a Looper Object's . Handler The analysis of the creation process of is completed , Now I finally understand .

Let's sum up ,Handler The creation of depends on Looper Of . The main thread creates one by default Looper Object's . every last Looper Will be associated with a thread (ThreadLocal Encapsulated Looper). every last Looper A message queue will be encapsulated in the . thus ,handler,Looper,MessageQueue,Thread The four roles are related , You have me , I have you. . handler Create in main thread , Because it is associated with the message queue of the main thread , like that handler Of handleMessage Method will execute in the main thread , So this is updating UI It's thread safe .

Go on , There are still many unsolved problems I believe you want to know more about Handler How to send messages . Usually we create a Message object , And pull some data from the server , Mark , Assign parameters to Message Some fields of what,arg1,obj etc. ,handler call sendMessage Method to send , This data can be sent to the main thread , And then in handlerMessage Method to handle updates UI that will do .

Then we went from handler Of sendMessage Methods start looking for information

public final boolean sendMessage(Message msg) {
    return sendMessageDelayed(msg, 0);
 Copy code 

sendMessage Would call sendMessageDelayed Methods and message Object passing in , The second parameter is the delay time , Use sendMessage Method defaults to 0 Of . Then came sendMessageDelayed Method

public final boolean sendMessageDelayed(Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
 Copy code 

To work around , Will eventually call sendMessageAtTime Method , And will message Object passed into .
Continue to follow up sendMessageAtTime Method ,

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    return enqueueMessage(queue, msg, uptimeMillis);
 Copy code 

It analyzes , Creating Looper When the object , Will create a MessageQueue, So as long as Looper If it is created normally , The message queue is not empty . So to the last line enqueueMessage Method , Source code is as follows :

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { = this;
    if (mAsynchronous) {
    return queue.enqueueMessage(msg, uptimeMillis);
 Copy code 

You can see that the last line calls MessageQueue Of enqueueMessage Method . Be careful : It's posted on it enqueueMessage yes Handler Methods , No MessageQueue Of , It's just a layer of packaging , The operation of the real queue message queue is, of course MessageQueue in . And from the first line = this We can know ,msg Of target Field , In fact, that is handler.

MessageQueue Of enqueueMessage The source code of the method is as follows :

boolean enqueueMessage(Message msg, long when) {
    if ( == null) {
        throw new IllegalArgumentException("Message must have a target.");
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");

    synchronized (this) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
           + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            return false;

        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // New head, wake up the event queue if blocked.
   = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // Inserted within the middle of the queue. Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            needWake = mBlocked && == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p =;
                if (p == null || when < p.when) {
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
   = p; // invariant: p ==
   = msg;

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
    return true;
 Copy code 

Messagequeue There is an object in mMessage Used to point to the current incoming msg, The latest news . And just now sendMessageAtTime(Message msg, long uptimeMillis) Method , The second parameter specifies the time , Then follow this here uptimeMillis To sort messages , And the result of my analysis Is to point to the next message , In this way, each message is related in chronological order , The message at the top points to the message at the bottom .

copyright notice
author[Sniper 000],Please bring the original link to reprint, thank you.

Random recommended