前言 Handler 是什么
看看官方的解释: A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler it is bound to a Looper. It will deliver messages and runnables to that Looper’s message queue and execute them on that Looper’s thread.
简单的来说:Handler 是一个消息处理者:可以向 Handler 发送 Message,这些 Message 会被 Looper 在对应的线程上执行。
Handler、Looper、MessageQueue 之间的关系
三者的类图如下:
三者的对应关系如下: 一个 Looper 对应一个 MessageQueue,且一个 Looper 对应一个专属的线程,每个线程最多只能有一个 Looper。一个 Looper 可以被多个 Handler 持有,所有多个 Handler 可以对应一个 Looper。
数据流图
Message:消息承载者
MessageQueue:消息队列,管理 Message 入队和出队
Looper:不断循环执行,将 Message 分配给对应的 Handler 处理
Handler:用于向 MessageQueue 发送 Message 和处理相应的事件
使用 常规 参考:Android多线程-有用的Handler
工具类 1 2 3 4 5 6 7 8 9 10 11 12 13 object UIHandler { private val uiHandler = Handler(Looper.getMainLooper()) fun post (runnable: Runnable ) { uiHandler.post(runnable) } fun postDelayed (runnable: () -> Unit , delayedMillis: Long ) { uiHandler.postDelayed(runnable, delayedMillis) } }
Handler
初始化 Handler 的构造方法被重载了很多次,但最终都会走入下面两个方法之一。这两个方法的处理是一致的,都是保存入参到 mLooper、mQueue、mCallback、mAsynchronous 中。 如果不传入 Looper 参数,会通过 Looper#myLooper 方法拿到当前调用线程的 Looper 使用。
在 Looper#myLooper 之前会通过反射检测是否存在内存泄漏,关于内存泄漏的例子以及解法可以参考:Android多线程-有用的Handler
在 Looper#myLooper 之后会判断拿到的 Looper 是否为空,如果为空就会抛出异常,后续介绍 Looper 时会解释这里的异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public Handler (Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0 ) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } mLooper = Looper.myLooper(); if (mLooper == null ) { throw new RuntimeException( "Can't create handler inside thread " + Thread.currentThread() + " that has not called Looper.prepare()" ); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; } public Handler (Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }
消息发送 消息发送的方法有很多种,总的来说有 3 类:
postxxx:入参是一个 Runnable 参数,会通过 Handler#getPostMessage 方法包装成 Message 类型参数。这个 Runnable 参数会保存到 Message#callback 中。
sendxxx:入参是一个 Message 参数,无需封装
sendEmptyxxx:入参是一个 int 参数,会通过 Message#obtain 方法包装成 Message 类型参数。这个 int 参数会保存到 Message#what 中。
大部分的方法都会走到 sendMessageAtTime 方法中,除了 postAtFrontOfQueue 方法,它调用的是 sendMessageAtFrontOfQueue。所以我们只需要深入下面这两个方法就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public boolean sendMessageAtTime (Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null ) { return false ; } return enqueueMessage(queue, msg, uptimeMillis); } public final boolean sendMessageAtFrontOfQueue (Message msg) { MessageQueue queue = mQueue; if (queue == null ) { return false ; } return enqueueMessage(queue, msg, 0 ); }
消息入队
通过分析 sendMessageAtTime 方法和 sendMessageAtFrontOfQueue 方法,发现它们最终都会调用到 enqueueMessage 方法。enqueueMessage 方法并没有做过多的处理:
为 Message 绑定执行的 Handler
按需标记 Message 是否是异步的,后续会解释这里的异步
调用 MessageQueue#enqueueMessage 方法将消息入队,后续在 MessageQueue 中分析。
1 2 3 4 5 6 7 8 9 private boolean enqueueMessage (MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this ; if (mAsynchronous) { msg.setAsynchronous(true ); } return queue.enqueueMessage(msg, uptimeMillis); }
消息处理 消息的处理在 Looper 和 MessageQueue 模块,它们处理消息会通过 Message#target 调用到 Handler#dispatchMessage 方法。
Handler 分发消息的顺序:
Message#callback
Handler#mCallback
Handler#handleMessage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public void dispatchMessage (Message msg) { if (msg.callback != null ) { handleCallback(msg); } else { if (mCallback != null ) { if (mCallback.handleMessage(msg)) { return ; } } handleMessage(msg); } } private static void handleCallback (Message message) { message.callback.run(); }
Handler#executeOrSendMessage 方法(该方法已经被标记为 hide)是一种消息发送的优化实现,它会先判断调用线程的 Looper 和当前 Handler#mLooper 是否一致。如果一致,直接调用 Handler#dispatchMessage 处理消息,否则调用 Handler#sendMessage 处理。
消息移除 消息是否存在和移除消息分别通过调用 hasMessages/hasCallbacks 和 removeMessages/hasCallbacks 实现。它们最终都会调用到 MessageQueue 中的方法,这里也放到后续的 MessageQueue 中分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public final boolean hasMessages (int what) { return mQueue.hasMessages(this , what, null ); } public final boolean hasCallbacks (Runnable r) { return mQueue.hasMessages(this , r, null ); } public final void removeMessages (int what) { mQueue.removeMessages(this , what, null ); } public final void removeCallbacks (Runnable r) { mQueue.removeMessages(this , r, null ); }
超时机制 通过 Handler#runWithScissors 方法(该方法已经被标记为 hide)就可以实现超时机制,但是如果调用线程的 Looper 和当前 Handler#mLooper 一致,就会直接执行。
1 2 3 4 5 6 7 8 9 10 11 public final boolean runWithScissors (Runnable r, long timeout) { if (Looper.myLooper() == mLooper) { r.run(); return true ; } BlockingRunnable br = new BlockingRunnable(r); return br.postAndWait(this , timeout); }
超时机制的原理是 BlockingRunnable#postAndWait 方法,它是通过 wait(delay) 阻塞当前线程实现的。当任务执行完成时线程就会被 notifyAll 唤醒,当任务超时也会被唤醒然后返回 false。
参考文档:面试官:” Handler的runWithScissors()了解吗?为什么Google不让开发者用?”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 private static final class BlockingRunnable implements Runnable { private final Runnable mTask; private boolean mDone; public BlockingRunnable (Runnable task) { mTask = task; } @Override public void run () { try { mTask.run(); } finally { synchronized (this ) { mDone = true ; notifyAll(); } } } public boolean postAndWait (Handler handler, long timeout) { if (!handler.post(this )) { return false ; } synchronized (this ) { if (timeout > 0 ) { final long expirationTime = SystemClock.uptimeMillis() + timeout; while (!mDone) { long delay = expirationTime - SystemClock.uptimeMillis(); if (delay <= 0 ) { return false ; } try { wait(delay); } catch (InterruptedException ex) { } } } else { while (!mDone) { try { wait(); } catch (InterruptedException ex) { } } } } return true ; } }
其他 View.post
View#post 也是一种子线程更新 UI 的方式,它本质上也是通过 Handler 实现。它的 Handler 是从 AttachInfo 获取的,因此存在调用时 AttachInfo 还没有赋值的场景。
系统使用 HandlerActionQueue 暂存这些事件,当 View#dispatchAttachedToWindow 被调用时就会触发 HandlerActionQueue#executeActions 方法,处理暂存的事件。
1 2 3 4 5 6 7 8 9 public boolean post (Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null ) { return attachInfo.mHandler.post(action); } getRunQueue().post(action); return true ; }
Activity.runOnUiThread
Activity#unOnUiThread 也是一种子线程中更新 UI 的方式,它本质上也是通过 Handler 实现
1 2 3 4 5 6 7 public final void runOnUiThread (Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
Looper
Looper 是什么?在刚才 Handler 源码中似乎没有看到它的具体调用,只看到 Handler 将 Looper 持有的 MessageQueue 保存到自己的成员变量中。我们可以从 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.
从注释中我们可以知道它是处理线程的消息循环,线程默认是没有的,需要调用 Looper#prepare 方法创建,再调用 Looper#loop 方法处理消息。官方给出的例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class LooperThread extends Thread { public Handler mHandler; public void run () { Looper.prepare(); mHandler = new Handler() { public void handleMessage (Message msg) { } }; Looper.loop(); } }
初始化 通过官方的例子,我们知道了每个线程都需要调用 Looper#prepare 方法创建 Looper。Looper 创建的同时会创建 MessageQueue 实例。Looper 通过使用 ThreadLocal 存储每个线程的 Looper 实例,quitAllowed 标志这个 Looper 能否退出,默认主线程不可以退出,子线程可以退出。 如果不创建的话,Handler 初始化的时候就会抛出异常:Can't create handler inside thread that has not called Looper.prepare()。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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)); } 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 Looper (boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
一般我们在子线程使用 Handler 确实因为没有调用 Looper#prepare 而出现这个异常,但是主线程为什么可以直接创建 Handler 呢? 肯定是因为系统在某个地方帮我们处理了这份工作,系统处理的位置就在 ActivityThread#main 方法中:
1 2 3 4 5 6 7 8 9 10 11 12 13 public final class ActivityThread extends ClientTransactionHandler { public static void main (String[] args) { Looper.prepareMainLooper(); Looper.loop(); } }
运行 要想 Looper 跑起来还得调用 Looper#loop 方法,方法的核心部分是一个死循环,用于处理 Message。
调用 MessageQueue#next 方法,获取到待处理的 Message
调用 Observer#messageDispatchStarting 方法通知 Observer 开始处理消息
通过 Message#target 调用 Handler#dispatchMessage 处理消息
如果消息处理成功,调用 Observer#messageDispatched 方法通知 Observer 消息处理成功
如果消息处理失败,调用 Observer#dispatchingThrewException 方法通知 Observer 消息处理失败
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public static void loop () { final Looper me = myLooper(); me.mInLoop = true ; final MessageQueue queue = me.mQueue; for (;;) { Message msg = queue.next(); final Observer observer = sObserver; Object token = null ; if (observer != null ) { token = observer.messageDispatchStarting(); } try { msg.target.dispatchMessage(msg); if (observer != null ) { observer.messageDispatched(token, msg); } } catch (Exception exception) { if (observer != null ) { observer.dispatchingThrewException(token, msg, exception); } throw exception; } finally { } msg.recycleUnchecked(); } }
退出 Looper 退出的方法有两个 quit、quitSafely,它们都是通过调用 MessageQueue#quit 方法实现的,后续在 MessageQueue 中分析。
1 2 3 4 5 6 7 public void quit () { mQueue.quit(false ); } public void quitSafely () { mQueue.quit(true ); }
Message
消息类型 可以通过 Message#setAsynchrouns 方法设置消息的类型,正常情况下的 Message 都是同步消息。 如果你想当前的消息不受 Looper 同步屏障(synchronization barriers)的约束,那么可以将 Message 标记为异步消息即可。
关于同步屏障的内容,会在 MessageQueue 部分详细介绍
对象池 为了减少 Message 的创建开销,Message 本身提供了对象池的能力。
创建
通过 Message#obtain 方法就可以从对象池中拿到一个 Message,如果对象池没有消息就会自动创建一个 Message。
1 2 3 4 5 6 7 8 9 10 11 12 13 public static Message obtain () { synchronized (sPoolSync) { if (sPool != null ) { Message m = sPool; sPool = m.next; m.next = null ; m.flags = 0 ; sPoolSize--; return m; } } return new Message(); }
销毁
当 Message 使用完毕后,MessageQueue 会通过 Message#recycle 方法将使用后的 Message 放入对象池中。对象池中最多容纳 MAX_POOL_SIZE 个 Message。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public void recycle () { if (isInUse()) { return ; } recycleUnchecked(); } void recycleUnchecked () { flags = FLAG_IN_USE; what = 0 ; arg1 = 0 ; arg2 = 0 ; obj = null ; replyTo = null ; sendingUid = UID_NONE; workSourceUid = UID_NONE; when = 0 ; target = null ; callback = null ; data = null ; synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) { next = sPool; sPool = this ; sPoolSize++; } } }
MessageQueue
初始化 在 Looper 创建的同时,会在内部创建 MessageQueue。MessageQueue 初始化工作比较简单:
给是否允许退出的成员变量 mQuitAllowed 赋值
调用 Native 方法 nativeInit 构建 NativeMessageQueue,并用成员变量 mPtr 保存其指针。
1 2 3 4 MessageQueue(boolean quitAllowed) { mQuitAllowed = quitAllowed; mPtr = nativeInit(); }
消息入队
校验 Message 是否有 target,这里只允许插入正常消息,不允许插入同步屏障,如果没有就会抛出异常。校验 Message 是否已经被使用了,如果使用了就会抛出异常。校验 MessageQueue 是否正在退出,如果正在退出,会调用 Message#recycle 方法释放 Message。如果检测都通过了,就将 Message 标记为已使用。
找到 Message 插入的位置:
如果发生以下场景,就会将 Message 插在队列头部:
当前的 Message 队列是空的(p == null)
由 sendMessageAtFrontOfQueue 插入的 Message(when == 0)
插入的 Message 早于队列中最早的 Message(when < p.when)
如果不是插入到队列头部,那就会将 Message 插在队列中间:
遍历消息队列,直到到了队列末尾(p == null)或者找到了比插入的 Message 更晚的 Message(when < p.when)
是否需要唤醒队列,如果需要唤醒就会调用 Native 方法 nativeWake,需要唤醒的场景如下:
如果是插在头部:只要队列被阻塞了(mBlocked),就需要唤醒队列。这里本质是在唤醒最新的同步消息。
如果是插在中间:正常情况下是不需要唤醒队列的,除非队列被阻塞了(mBlocked)、且当前队头是同步屏障(p.target == null)、且这个 Message 是队列中最早的异步消息(msg.isAsynchronous()),这个时候才需要唤醒队列。这是本质是在唤醒最新的异步消息。
synchronized 原因:
可能有多个 Handler 绑定了同一个 Looper,这几个 Handler 在不同的线程中,这个时候如果它们发送消息的话,就会出现线程不安全的场景。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 boolean enqueueMessage (Message msg, long when) { if (msg.target == null ) { } synchronized (this ) { if (msg.isInUse()) { } if (mQuitting) { msg.recycle(); return false ; } msg.markInUse(); msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { msg.next = p; mMessages = msg; needWake = mBlocked; } else { 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; prev.next = msg; } if (needWake) { nativeWake(mPtr); } } return true ; }
同步屏障 同步屏障本质上也是一个 Message,特殊之处在于其 target 字段是空的,并且会有一个 token 字段。 这个 token 其实就是一个不断递增的 int 值。同步屏障的作用是为了让消息队列中的异步消息被优先执行。
同步屏障添加的方式只有一种,那就是调用 MessageQueue#postSyncBarrier 方法,根据时间将同步屏障插入到消息队列中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 private int postSyncBarrier (long when) { synchronized (this ) { final int token = mNextBarrierToken++; final Message msg = Message.obtain(); msg.markInUse(); msg.when = when; msg.arg1 = token; Message prev = null ; Message p = mMessages; if (when != 0 ) { while (p != null && p.when <= when) { prev = p; p = p.next; } } if (prev != null ) { msg.next = p; prev.next = msg; } else { msg.next = p; mMessages = msg; } return token; } }
移除同步屏障的方式也只有一种,那就是调用 MessageQueue#removeSyncBarrier 方法。但是这里需要注意一点:
如果待移除的同步屏障不是当前消息队列中的第一条,说明该消息屏障还没有发挥作用,不用唤醒队列。
如果待移除的同步屏障是当前消息队列中的第一条,并且消息队列为空或者接下来的是同步消息,那就需要唤醒队列,让同步消息得到执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public void removeSyncBarrier (int token) { synchronized (this ) { Message prev = null ; Message p = mMessages; while (p != null && (p.target != null || p.arg1 != token)) { prev = p; p = p.next; } if (p == null ) { throw new IllegalStateException("The specified message queue synchronization " + " barrier token has not been posted or has already been removed." ); } final boolean needWake; if (prev != null ) { prev.next = p.next; needWake = false ; } else { mMessages = p.next; needWake = mMessages == null || mMessages.target != null ; } p.recycleUnchecked(); if (needWake && !mQuitting) { nativeWake(mPtr); } } }
系统应用
ViewRootImpl 中的针对绘制消息的处理:
ViewRootImp#scheduleTraversals 中发送同步屏障消息,同时发送用于处理绘制的异步消息
ViewRootImp#doTraversal 中移除同步屏障消息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 void scheduleTraversals () { if (!mTraversalScheduled) { mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier(); mChoreographer.postCallback( Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null ); } } private void postCallbackDelayedInternal (int callbackType, Object action, Object token, long delayMillis) { synchronized (mLock) { if (dueTime <= now) { scheduleFrameLocked(now); } else { Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action); msg.arg1 = callbackType; msg.setAsynchronous(true ); mHandler.sendMessageAtTime(msg, dueTime); } } } void doTraversal () { if (mTraversalScheduled) { mTraversalScheduled = false ; mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier); if (mProfile) { Debug.startMethodTracing("ViewAncestor" ); } performTraversals(); if (mProfile) { Debug.stopMethodTracing(); mProfile = false ; } } }
消息出队
调用 Native 方法 nativePollOnce 以非阻塞当前线程的方式阻塞当前调用。第一次进入循环时,由于不知道待执行 Message 的状态,所以将超时时间 nextPollTimeoutMillis 设置为 0。这样就不会阻塞当前调用,可以拿到消息队列队头的 Message 了。
如果拿到的 Message 是同步屏障(target == null),就会遍历消息队列找到第一个异步 Message。如果不是且不为空,就会使用拿到的 Message 继续下面的处理。
如果 Message 的待执行时间大于当前时间,说明需要延迟处理,这时会更新 nextPollTimeoutMillis ,便于再一次进入循环时,nativePollOnce 可以阻塞调用。
如果 Message 需要处理了,会先将 mBlocked 字段设置为 false,从消息队列中取出,并标记为已使用
如果拿不到 Message,会将 nextPollTimeoutMillis 标志量设置为 -1,这样调用 nativePollOnce 方法后就会一直处于阻塞状态,直到调用 nativeWake 方法手动唤醒。
如果当前待执行的 IdleHandler 数量是默认值(pendingIdleHandlerCount < 0),并且消息队列为空(mMessages == null),或者最早待执行的消息需要在未来执行(now < mMessages.when),这个时候就会初始化 pendingIdleHandlerCount 字段。
如果存在待执行的 IdleHandler,就会遍历 mIdleHandlers 列表,执行 IdleHandler#queueIdle 方法
如果不存在待执行的 IdleHandler,会先将 mBlocked 字段设置为 true,直接进行下一次循环
如果还能继续往下执行,就会为了下一次循环重置标志量:
需要将 pendingIdleHandlerCount 设置为 0,因为 IdleHandler 只会在第一次循环的时候才有可能被执行
需要将 nextPollTimeoutMillis 设置为 0,因为走到这里的就表明肯定执行过 IdleHandler,这个时候 nextPollTimeoutMillis 就不准确了,所以需要将其置为 0。
死循环区别:
需要注意一点,Looper#loop 方法里面有一个死循环,MessageQueue#next 方法里面也有一个死循环。Looper#loop 中的是循环是为了不停的取出 Message,MessageQueue#next 中的循环是为了取出下一个 Message 的。
mBlocked 字段:
mBlocked 是用来标志 MessageQueue#next 有没有被 nativePollOnce 阻塞住调用:
MessageQueue#next 中第一次进入循环取 Message,假如这个时候可以拿到 Message,那么 mBlocked 就会被设置为 false
MessageQueue#next 中第一次进入循环取 Message,假如这个时候可以拿不到 Message,说明要么没有 Message,要么最新的 Message 在未来执行。
如果这个时候不存在待执行的 IdleHandler,那么就会将 mBlocked 就会被设置为 true,直接跳到下一次循环。这个时候就会被 nativePollOnce 阻塞住 nextPollTimeoutMillis 时间调用,用于等待下一个最新的消息
如果这个时候存在待执行的 IdleHandler,那么就会执行这些 IdleHandler。同时在循环的末尾将 pendingIdleHandlerCount 和 nextPollTimeoutMillis 重置为 0。这样在新的循环开始,就可以像第一次循环一样取 Message 且不用考虑 IdleHandler 的执行。
synchronized 原因:
虽然 MessageQueue#next 方法调用线程是固定的,但它仅仅是获取 Message,此时此刻可能存在其他线程正在插入 Message。所以这里的 synchronized 是用于解决 Message 插入和获取的线程冲突问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 Message next () { int pendingIdleHandlerCount = -1 ; int nextPollTimeoutMillis = 0 ; for (;;) { nativePollOnce(ptr, nextPollTimeoutMillis); synchronized (this ) { final long now = SystemClock.uptimeMillis(); Message prevMsg = null ; Message msg = mMessages; if (msg != null && msg.target == null ) { do { prevMsg = msg; msg = msg.next; } while (msg != null && !msg.isAsynchronous()); } if (msg != null ) { if (now < msg.when) { nextPollTimeoutMillis = (int ) Math.min(msg.when - now, Integer.MAX_VALUE); } else { mBlocked = false ; if (prevMsg != null ) { prevMsg.next = msg.next; } else { mMessages = msg.next; } msg.next = null ; msg.markInUse(); return msg; } } else { nextPollTimeoutMillis = -1 ; } if (mQuitting) { dispose(); return null ; } if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0 ) { mBlocked = true ; continue ; } if (mPendingIdleHandlers == null ) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4 )]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); } for (int i = 0 ; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null ; boolean keep = false ; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception" , t); } if (!keep) { synchronized (this ) { mIdleHandlers.remove(idler); } } } pendingIdleHandlerCount = 0 ; nextPollTimeoutMillis = 0 ; } }
消息移除 判断 Message 是否存在,其实就是遍历消息队列看能否找到符合条件的 Message。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 boolean hasMessages (Handler h, int what, Object object) { if (h == null ) { return false ; } synchronized (this ) { Message p = mMessages; while (p != null ) { if (p.target == h && p.what == what && (object == null || p.obj == object)) { return true ; } p = p.next; } return false ; } }
移除 Message 其实就是遍历消息队列,将符合条件的 Message 移除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 void removeMessages (Handler h, int what, Object object) { if (h == null ) { return ; } synchronized (this ) { Message p = mMessages; while (p != null && p.target == h && p.what == what && (object == null || p.obj == object)) { Message n = p.next; mMessages = n; p.recycleUnchecked(); p = n; } while (p != null ) { Message n = p.next; if (n != null ) { if (n.target == h && n.what == what && (object == null || n.obj == object)) { Message nn = n.next; n.recycleUnchecked(); p.next = nn; continue ; } } p = n; } } }
退出 退出方式有两种,一种是粗暴的直接退出,一种是将当前待执行的 Message 处理完再退出。
为什么我们可以在退出的时候执行完当前待处理的 Message 呢? 这是因为 MessageQueue#next 中,退出操作的判断位于返回消息之后。所以直到把队列中待执行的 Message 取完之前,是不会走到对 mQuitting 判断,然后执行 dispose 退出的位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 void quit (boolean safe) { if (!mQuitAllowed) { throw new IllegalStateException("Main thread not allowed to quit." ); } synchronized (this ) { if (mQuitting) { return ; } mQuitting = true ; if (safe) { removeAllFutureMessagesLocked(); } else { removeAllMessagesLocked(); } nativeWake(mPtr); } }
全部移除:遍历消息队列,将 Message 依次移除。
1 2 3 4 5 6 7 8 9 private void removeAllMessagesLocked () { Message p = mMessages; while (p != null ) { Message n = p.next; p.recycleUnchecked(); p = n; } mMessages = null ; }
移除未来的消息:遍历消息队列,根据 when 字段将未来待执行的 Message 依次移除。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 private void removeAllFutureMessagesLocked () { final long now = SystemClock.uptimeMillis(); Message p = mMessages; if (p != null ) { if (p.when > now) { removeAllMessagesLocked(); } else { Message n; for (;;) { n = p.next; if (n == null ) { return ; } if (n.when > now) { break ; } p = n; } p.next = null ; do { p = n; n = p.next; p.recycleUnchecked(); } while (n != null ); } } }
销毁 销毁的方式很简单,和初始化对应,通过调用 Native 方法 nativeDestroy 实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Override protected void finalize () throws Throwable { try { dispose(); } finally { super .finalize(); } } private void dispose () { if (mPtr != 0 ) { nativeDestroy(mPtr); mPtr = 0 ; } }
Native Native 部分参考:Handler Native 原理探究
这里可以先回答一个问题:Looper 里面通过死循环不停的获取消息并处理,不会卡死吗? 和正常的死循环不同,Looper 每次获取消息都会调用 nativePollOnce 方法。这个方法内部使用了 epoll 机制,如果没有可用的消息就会被阻塞住,此时线程就会释放掉 CPU 进入休眠状态直到有新的消息到来。可以参考:Handler详解4-epoll、looper.loop主线程阻塞 。
其他
HandlerThread 的原理:Android多线程-HandlerThread
Messager 的原理:Android进程间通信 Messenger 详解
参考