Android消息传递机制浅析

1.Looper、Handler、MessageQueue的关系

  • Looper 用于线程的消息循环,一个线程只能有一个Looper对象
  • Handler
  • 执行任务调度和发生一些操作(在未来某时刻)
  • 执行其他线程中的队列消息
  • MessageQueue 消息队列

一个Looper关联一个MessageQueue,并不断从MessageQueue中取出消息,提交给Handel处理。

2.Looper

以主线程为例。Looper的初始化过程是这样的。
代码地址:/frameworks/base/core/java/android/app/ActivityThread.java#main(String[] args)

Looper.prepareMainLooper();
xxxx
Looper.loop();

而非UI线程的初始化过程

Looper.prepare()
xxx
Looper.loop();

不管是主线程还是其他线程,都会调用prepare(boolean quitAllowed)方法,参数为是否允许退出循环,主线程是不允许的,而其他线程是允许的。

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

接下来看Looper的构造方法

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

从构造方法中可以看出,将Looper、MessageQueue、currentThread之间建立的关联。
那么,Looper对象是如何从消息队列中不断地取出消息呢?代码比较长,我们拆开来看。

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

取出和当前线程对应的Looper对象

    for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            msg.target.dispatchMessage(msg);

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            msg.recycleUnchecked();
        }
    }

上面的代码中去掉了一些日志代码。可以看到,死循环从MessageQueue中取出消息,并调用msg.target.dispatchMessage(msg)方法去消息小心,最后回收。

3.Handler

既然知道了Looper,那么我们需要知道消息是怎么来的。

Message msg = new Message();
msg.what = xxx;
msg.obj = xxx;
handler.sendMessage(msg);

我们通常都是通过上面的步骤去发送的,所以,追踪下代码。

sendMessage->sendMessageDelayed->sendMessageAtTime->enqueueMessage
到这里就来到了一个关键点了,我们看下代码。

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

还记得我们上面分发消息的地方么?同样有target,这个是什么呢?我们进Message的源码里一探究竟。

Handler target

好,是一个handler对象,也就是我们当前线程的一个handler对象,也就是发送消息的那个handler对象。所以,我们现在来看看handler的dispatchMessage方法。

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

调用关系和初始化的关系有关。

  • Message.obtain(Handler h, Runnable callback) 构造消息时,会调用handlerCallback(msg)方法
  • 初始化Handler的构造函数带CallBack参数是,调用mCallBack的 handleMessage(msg)方法
  • 否则,调用handlerMessage(msg)方法。

回到enqueueMessage方法,发现是通过调用MessageQueue的enqueueMessage方法来插入消息的。

4.MessageQueue

消息队列,字面意思是消息队列,然而我们知道,队列的方式是先进先出,而我们的消息时候时间调度的,因此,并不符合先进先出的思想,所以,消息队列实际上是个链表,这样我们才能往任意位置插入消息。enqueueMessage的代码如下:

    boolean enqueueMessage(Message msg, long when) {
        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();
            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.
                msg.next = 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 && 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.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

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

上面的步骤是这样子的。

  • 判断是否关联了handler
  • 判断是否用过(已经插入到链表中的)
  • 当前队列是否处在退出状态
  • 退出状态 回收资源,插入链表失败
  • 不是退出状态
    • 改变Message的状态为已经use,并获取message的when时间
    • 在链表中找到合适的位置插入
      • 和链表头结点比较时间,如发生时间在头结点消息之前,插入到头结点
      • 死循环,找到该消息比链表中的消息早发生的消息,插入到那条消息前面,否则就插入到链表表尾

在最前面Looper里,一直通过queue.next()去读取链表里的消息,所以,我们来看下next方法。由于next的方法比较长,我们一段一段来看。

                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

  • 假如当前Message不为null 但是没和handler关联的话,就找下一个消息,知道找到不是null也关联到handler的Message

  • 如果当前时间小于Message的when的话,就计算时间差,并赋值给nextPollTimeoutMillis

  • 不小于的话

    • 假如步骤1中链表头的消息没关联handler,就将步骤1中找出的不是null也关联了handler的Message的上一条Message.next指向该Message.next(这里有点绕,其实就相当于在链表中移除了改消息),并返回该消息
    • 否则,将mMessages(表头)指向msg.next(也是移除了该消息)
  • 下面的代码忽略(ps:我看不懂...)

5.总结

当然,这些东西里面我没有介绍ThreadLocal这个,想了解的朋友们去Google吧(百度不是出事了么,嘿嘿)。
Android中的消息传递机制是一个非常重要的东西,我们需要简单的了解下他的简单原理,所以,大家也去看看源代码吧。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容