Handler通信 - 源码分析

一、 MessageQueue 消息队列

//线程中更新 UI 的时候经常是调用 sendMessage() 
public final boolean sendMessage(Message msg){
    return sendMessageDelayed(msg, 0);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis){
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    // SystemClock.uptimeMillis() + delayMillis   当前时间加上延迟时间
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

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);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    //这里已经绑定了Handler,后面的发送消息就是通过该handler调用
    msg.target = this;
    // new Handler 源码的时候是 false 
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

enqueueMessage() 方法:

boolean enqueueMessage(Message msg, long when) {
        // 判断有没有 target 
        if (msg.target == 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(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }
            // 标记消息正在使用中
            msg.markInUse();
            //wen存放的是延时时间
            msg.when = when;
            Message p = mMessages;//第一次这里的p是空的
            boolean needWake;
            // 第一次添加数据到队列中,或者当前 msg 的时间小于 mMessages 的时间
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                // 把当前 msg 添加到链表的第一个
                msg.next = p;  //第一次是空的
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // 不是第一次添加数据,并且 msg 的时间 大于 mMessages(头指针) 的时间
                // 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 && p.target == null && msg.isAsynchronous();
                Message prev;
                //最核心的部分就是这个死循环
                for (;;) {
                    // 不断的遍历找到合适的位置
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                // 把当前 msg 插入到列表中
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

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

二、Loop消息循环
1)似乎没有调用handleMessage()方法,不着急,先分析一个现象,当我们在子线程中直接new Handler()会报错

new Thread(){
  @Override
  public void run() {
      Handler handler = new Handler();
  }
}.start();
2)需要如下写法才正常
new Thread(){
    @Override
    public void run() {
        Looper.prepare();
        Handler handler = new Handler();
        Looper.loop();
    }
}.start();

3)分析:为什么在Activity中直接写确没问题呢?
1. ActivityThread 的 main() 方法中系统早就帮我们写好了:

public static void main(String[] args) {
    // ... 省略部分代码
    
    Looper.prepareMainLooper();

    ActivityThread thread = new ActivityThread();
    thread.attach(false);

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

    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}
  1. Looper.prepareMainLooper() 和 Looper.loop()
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

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));
}

public static @Nullable Looper myLooper() {
    return sThreadLocal.get();
}

主要还是 ThreadLocal 的 set 方法,用来保证一个线程只有一个 Looper 对象,这样就保证了线程的安全。接下来看一下 Looper.loop() 这行:

public static void loop() {
    final Looper me = myLooper();
    final MessageQueue queue = me.mQueue;
    // 一个死循环
    for (;;) {
        // 不断的从消息队列里面取消息
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        try {
            // 通过 target 去 dispatchMessage 而 target 就是绑定的 Handler
            msg.target.dispatchMessage(msg);
        } finally {
            // 消息回收循环利用
            msg.recycleUnchecked();
        }
    }
}

三、总结

1
图片.png

1)Looper.prepareMainLooper() 创建了一个 Looper 对象,而且保证一个线程只有一个 Looper;Looper.loop() 里面是一个死循环,不断的从 消息队列 MessageQueue 中取消息,然后通过 Handler 执行。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容