> Chapter 10

Android的消息机制 Android消息机制概述 Android的消息机制主要是指Handler的运行机制以及Handler所附带的MessageQueueLooper的工作过程.

  • 一个Thread包含一个Looper
  • 一个Looper包含一个MessageQueue
  • 一个Handler包含一个Looper和一个Messagequeue(和Looper中的是同一个)
Handler通过sendMessage()post()方法将Message放到MessageQueue中, 然后Looper.loop()方法不停的循环从MessageQueue中取Message,成功取出后,通过在loop()中调用message.target.dispatchMessage()方法(message.target其实就是发送MessageHandler)来执行Handler.handleMessage方法.
总结:跨线程的关键是Handler中的Looper是定义Handler时所在Thread的Looper, MessageQueue也是这个Thread的Looper中的MessageQueue,所以之后我们不管在哪个线程调用Handler.sendMessage()方法,Message都会被发送到定义Handler时的LooperMessageQueue中, 因此Handler.dispatchMessage()都是在定义Handler时的那个线程中执行的。
ThreadLocal ThreadLocal是一个线程内部的数据存储类, 它可以保证, 同一个变量, 在不同的线程中, 使用的都是不同的副本。
Looper就是利用ThreadLocal来保证它在每个Thread中都是独立存在的。
private ThreadLocal mBooleanThreadLocal = new ThreadLocal(); mBooleanThreadLocal.set(true); Log.d(TAG, "MainThread mBooleanThreadLocal=" + mBooleanThreadLocal.get()); new Thread("Thread1"){ @Override public void run(){ mBooleanThreadLocal.set(false); Log.d(TAG, "Thread1 mBooleanThreadLocal=" + mBooleanThreadLocal.get()); }new Thread("Thread1"){ @Override public void run(){ Log.d(TAG, "Thread2 mBooleanThreadLocal=" + mBooleanThreadLocal.get()); } }

输出结果为:
MainThread mBooleanThreadLocal=true Thread1 mBooleanThreadLocal=false Thread2 mBooleanThreadLocal=null

从上面的结果中可以发现, 虽然看起来主线程和Thread1Thread2使用的都是同一个ThreadLocal对象, 但是他们其实操作的都是不同的对象。
具体的实现原理可以参考这篇文章
MessageQueue工作原理 MessageQueue主要包含两种操作:插入(enqueueMessage())和读取(next()).
MessageQueue内部实现并不是一个队列, 而是一个单链表.
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; }

enqueueMessage()的实现可以看出它的主要操作就是单链表的插入。
Message next() { // Return here if the message loop has already quit and been disposed. // This can happen if the application tries to restart a looper after quit // which is not supported. final long ptr = mPtr; if (ptr == 0) { return null; }int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (; ; ) { if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); }nativePollOnce(ptr, nextPollTimeoutMillis); 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; }//省略... } } }

next()方法其实是一个无限循环的方法,如果消息队列没有消息,那么next()方法会一直堵塞在那里。当有新消息来时,next()方法会返回这条消息并将其从单链表中移除。
Looper工作原理
  • 我们在自定义的Thread中通过Looper.prepare()来进行初始化Thread本身的Looper,通过调用Looper.loop()方法来循环取出MessageQueue中的Message
    Handler在构造方法中从通过Looper.myLooper()方法取出当前ThreadLooper(在Looper.prepare()setsThreadLocal中的Looper)
    new Thread("Thread#1") { @Override public void run(){ Looper.prepare(); Handler handler = new Handler(); Looper.loop(); } }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 Handler(Callback callback, boolean async) { //省略... mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }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 { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } //省略... } }

  • Looper会在它的构造方法中初始化属于它的MessageQueue
    private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }

  • Looper提供了quit()quitSafely()两个方法来退出, 两者的区别是quit()会直接退出, quitSafely()会把MessageQueue()已有的消息处理完后再退出
  • 在子线程中使用完Looper后需要调用quit()方法来退出, 否则那个子线程就会一直处于等待状态
    public void quit() { mQueue.quit(false); }

Handler工作原理 Handler的主要工作包含发送和接收过程。消息的发送可以通过post系列方法以及sendMessage方法实现,但是post的一系列方法最终是通过sendMessage系列方法实现的。
sendMessage系列方法发送一条消息的典型过程如下所示:
public final boolean sendMessage(Message msg){ return sendMessageDelayed(msg, 0); }public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } 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) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }

可以发现Handler发送消息的过程仅仅是向MessageQueue插入了一条消息,MessageQueue通过next方法就会将这条Message返回给Looper,最终消息由Looper交由Handler处理,即HandlerdispatchMessage方法会被调用,这时Handler就进入了消息处理的阶段。dispatchMessage()如下所示:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }

【> Chapter 10】首先,检查msg.callback是否为null, 不为null就通过handleCallback()来处理消息。
其次,如果mCallback 不为null,就通过mCallback.handleMessage(msg)来处理消息。
最后,调用最常见的handleMessage(msg)来处理消息。
  • msg.callback就是我们调用Handlerpost系列方法所传递的Runnable参数。
  • mCallback是一个接口,Handler提供了一个构造方法,使我们可以传递一个Callback作为参数,这样我们就不用重写Handler
    public interface Callback { public boolean handleMessage(Message msg); }Handler handler = new Handler(callback);

    推荐阅读