从源码的角度解析Android消息机制

1、概述

相信大家对Handler的使用再熟悉不过了,Handler也经常被我们应用于线程间通信。下面看一段很经典的代码:

 class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

当我们在主线程或者在其它线程获取到LooperThread线程中的mHandler实例并调用mHandler.sendMessage()时,消息会传递到LooperThread线程中并在handleMessage方法中执行对消息的特定处理。不知道大家有没有想过为什么在一个线程发送消息另一个目标线程能够正确接收并做相应处理?这篇文章就带领大家从源码的角度一步步理解Android的消息机制。Android的事件处理是基于消息循环的,Android的消息机制离不开Looper、MessageQueue、Handler,其实理解Android的消息机制就是理解以上三者的作用与联系。

2、Looper

我们先来看看官方文档对Looper的解释

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.

从中我们可以知道,Looper是一个线程的消息循环器,线程默认是没有消息循环器的。我们可以通过prepare方法为一个线程创建消息循环器,然后通过调用loop方法处理消息直至循环终止。我们看看调用prepare方法后都发生了什么:

public final class Looper {
    private static final String TAG = "Looper";

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;

    private Printer mLogging;

     /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    public static void prepare() {
        prepare(true);
    }

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

在prepare方法中首先会通过调用ThreadLocal的get方法判断当前线程的消息循环器Looper是否为空,为空则通过Looper构造器创建实例,否则抛出异常。从异常信息我们可以知道一个线程只有一个Looper。在这里ThreadLocal的作用是关联线程和Looper,一个线程对应一个Looper,即调用prepare方法的线程会和prepare方法创建的Looper实例关联,且一个线程和唯一一个Looper关联,当第二次调用prepare方法时程序会抛出异常。接下来我们看看通过Looper构造方法实例化对象时发生了什么:

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

从源码我们能够看到实例化Looper时,会初始化消息队列MessageQueue(MessageQueue后续会详解)以及记录当前Looper关联的线程。MessageQueue作为Looper的成员变量在此时也与Looper建立了关联。接下来我们看看Looper的另外一个方法loop:

 /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

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

            // This must be in a local variable, in case a UI event sets the logger
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            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();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

从以上源码我们不难理解,首先通过myLooper()方法获取当前线程的Looper实例,如果为空则抛出必须先调用prepare方法为当前线程关联Looper的异常信息。接下来进入到loop方法中最重要的部分是一个for(;;)死循环。在循环中Looper关联的消息队列MessageQueue会通过调用next方法获取消息队列中的消息Message,并且循环会把消息分发给相应的目标对象。 msg.target.dispatchMessage(msg);这行代码即是对消息的分发。其中target是Handler实例,即调用sendMessage方法发送的消息所关联的Handler。Handler调用dispatchMessage分发消息最总会调用handleMessage方法这样就进入到了我们对消息的处理流程(后文会对Handler进行详解,这里提到只是为了便于大家理解)。我们看到Message msg = queue.next(); // might block这行源码做了注释,意思是next方法的调用可能会发生阻塞。也就是说当消息队列中有消息时,next方法会返回消息对象否则当前线程会一直阻塞直至队列中有新消息把当前线程唤醒。不知道大家注意到了loop方法的注释没有,Be sure to call * {@link #quit()} to end the loop.我们要调用quit方法结束循环。调用quit方法最终会使得MessageQueue next方法返回null,当为空时会跳出for死循环,这样线程最终才可能结束生命。如果线程在处理完自己的任务后不调用quit方法,线程将一直阻塞或被新的无用消息唤醒而最终无法终止,这无疑是对资源的浪费。
至此,Looper的源码分析完了,当然有一些方法并没有分析(请大家自行阅读),现在我们对Looper做一个总结:一个线程唯一对应一个Looper,一个Looper唯一关联一个消息队列MessageQueue。Looper不断从消息队列中取出消息并分发给目标对象。还有要注意的是线程处理完相应任务后要调用quit方法结束循环,否则会造成不必要的资源浪费。

2、MessageQueue

接下来我们继续分析MessageQueue,首先我们还是看官方文档的解释

/**
 * Low-level class holding the list of messages to be dispatched by a
 * {@link Looper}.  Messages are not added directly to a MessageQueue,
 * but rather through {@link Handler} objects associated with the Looper.
 * 
 * <p>You can retrieve the MessageQueue for the current thread with
 * {@link Looper#myQueue() Looper.myQueue()}.
 */

官方文档解释的很清楚,MessageQueue持有待分发的消息列表。我们通常不会直接操作MessageQueue插入消息而是通过Handler。我们可以通过Looper类的方法myQueue获得当前线程的MessageQueue。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;
    }

我们能够看到前面几行代码对消息状态进行了判断,包括如果消息分发的目标对象为空或者消息已经被使用将抛出异常,以及如果终止了消息循环,消息将不会插入到队列中并且返回false。接下来是消息入队的核心代码,可以看到是典型的链表结构:如果表头为空则创建表头,否则将数据插入到表的末尾。通过分析代码我们也能够知道,虽然MessageQueue字面意思是消息队列,但它真正的内部数据结构并不是队列而是普通链表。接下来我们继续看出队方法next的源码,我们截取其中比较重要的一部分

synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                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实例,并且表头向下移动一位。上文我们提到了用Looper 的quit方法终止消息循环,其实最终调用的是MessageQueue的quit方法。quit方法有个safe参数,表示是否安全终止循环。所谓安全是当调用quit方法后消息队列中无法插入新的消息,但是循环可能不会立即终止,直至消息队列中待分发的消息(如果有)分发完毕。不安全的终止与之相反,消息循环会立即终止,新的消息也无法插入。至此,MessageQueue的主要方法分析完毕了,其它的一些方法如removeMessage、quit等请大家自行阅读分析,下面我们队MessageQueue做一个总结:MessagQueue的作用主要是存储消息,并且对外提供一些接口对消息操作如插入消息、取出消息、移除消息等。

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

推荐阅读更多精彩内容