源码分析|Android Handler(手把手带你深入分析 Handler机制源码)

Android的Handler机制,我相信是每一位小伙伴面试都经历过的一道题目,Handler机制可以说是Android的很基础但是很重要的内容,因为深入理解了它,很多内容理解起来就变的轻而易举了,比如AsyncTaskHandlerThread, IntentService内部都用到了Handler机制,今天我们就从源码角度来分析它。
为什么要有Handler机制 ?
  • 首先我们放一张图来直观感受一下Handler机制的原理
    源码分析|Android Handler(手把手带你深入分析 Handler机制源码)
    文章图片
  • Handler机制对于Android开发者来说是为了解决线程切换的问题,为什么要线程切换呢?是因为Android开发规范的限制,我们不能在子线程中更新UI(实际上子线程是可以更新UI的,只是不建议这么做),会造成"Only the original thread that created a view hierarchy can touch its views."异常,这个异常在类ViewRootimpl中有一个方法checkThread,如下:
    void checkThread() { if (mThread != Thread.currentThread()) { throw new CalledFromWrongThreadException( "Only the original thread that created a view hierarchy can touch its views."); } }

  • 但是又因为主线程不能进行耗时操作,比如网络I/O等,会造成ANR异常,这些耗时操作得在子线程中执行。
  • 所以问题就来了,我们得在主线程UI,但是不能在主线程执行耗时操作;而子线程恰好相反,可以在子线程执行耗时操作,但是不能在子线程更新UI,怎么将它们进行方便的切换呢?解决线程间的切换-这就是Handler机制存在的意义
分析源码之前,先看一下常用的在子线程中更新UI的Android原生方法,以及使用Handler机制封装起来的类都有哪些:
  • 通过activity.runOnUiThread(Runnable action)来在子线程中更新UI, 我们看到如果当前线程不是主线程,使用的是Handler机制,如果是主线程就直接执行run方法。
    final Handler mHandler = new Handler(); public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }

  • 通过view.post(Runnable action)或者view.postDelayed(Runnable action, long delayMillis)来在子线程中更新UI,源码如下,我们可以看到如果attachInfo != null, 使用的其实还是Handler机制。有的小伙伴就要问了,那这个AttachInfo是什么意思呢?在哪里赋值的?如果attachInfo为空呢,怎么办?还有下面的getRunQueue().post(action); 的逻辑是什么?这些问题限于篇幅,可以看[Android源码解析] View.post到底干了啥这篇文章,里面有详细的讲解,这里简单说一下最后一个问题,其实这里只是将需要执行的任务缓存起来,最终还是通过Handler机制来处理的。
    final Handler mHandler public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); }// Postpone the runnable until we know on which thread it needs to run. // Assume that the runnable will be successfully placed after attach. getRunQueue().post(action); return true; }

  • 直接使用Handler了,在子线程中通过handler.sendMessage(message)进行使用,这也是我们今天要重点分析的Handler机制源码部分。但是要注意内存泄露,关于Handler的内存泄露部分在文章Android性能优化(二)——内存泄漏中有详细介绍。
  • 再有就是AsyncTaskHandlerThread,IntentService等,它们内部都封装了Handler,想要详细了解的可以看Android 多线程:AsyncTask的原理及其源码分析进行了解。
Handler机制元素:
  • Handler消息机制有四个主要元素,分别是Message,MessageQueue,Looper,Handler, 其实还有一个元素也是很重要的,在Looper中,它是ThreadLocal
  • Message就是我们要放在队列中被处理的对象。
  • 其中MessageQueue是一个消息队列,里面存储的自然是消息,但是它不是一个队列,而是一个链表的形式,它仅仅有存储消息的功能,并不能处理消息。
  • Looper是真正处理消息的地方,它会进入一个无限循环从消息队列中查询是否有新的消息,如果有的话就处理,没有的话就一直等待。
  • Handler是发送消息的类,会将消息发送到消息队列中,然后Looper去循环查询消息,进行处理。
  • ThreadLocal是一个神奇的类,它在Looper.prepare()方法中使用到了,神奇之处在于它会提供线程隔离,使各个线程之间的数据互相不会影响,尽管使用的是同一个mThreadLocal对象。在Handler的构造方法通过Looper.myLooper(),就能获取每一个线程的Looper, 子线程想要获取looper是得执行Looper.prepare()的,不然会报异常的,但是在主线程中的ActivityThread中的main方法已经执行了Looper.prepare()方法,所以我们可以直接在主线程使用Handler。
Handler机制源码分析:
MessageQueue
  • MessageQueue中有两个主要的方法,一个是消息入队列的enqueueMessage(msg, when)方法,一个是从队列中取消息的next()方法。其实MessageQueue并不是真正的队列,它的内部而是维护了一个单链表的结构,因为链表插入删除比较快。
  • 我们先看enqueueMessage(msg, when)方法,主要就是根据when的大小,将消息插入队列中。
    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; }

  • 下面我们看next方法的源码实现:
    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; }// Process the quit message now that all pending messages have been handled. if (mQuitting) { dispose(); return null; }// If first time idle, then get the number of idlers to run. // Idle handles only run if the queue is empty or if the first message // in the queue (possibly a barrier) is due to be handled in the future. if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) { pendingIdleHandlerCount = mIdleHandlers.size(); } if (pendingIdleHandlerCount <= 0) { // No idle handlers to run.Loop and wait some more. mBlocked = true; continue; }if (mPendingIdleHandlers == null) { mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)]; } mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers); }// Run the idle handlers. // We only ever reach this code block during the first iteration. for (int i = 0; i < pendingIdleHandlerCount; i++) { final IdleHandler idler = mPendingIdleHandlers[i]; mPendingIdleHandlers[i] = null; // release the reference to the handlerboolean keep = false; try { keep = idler.queueIdle(); } catch (Throwable t) { Log.wtf(TAG, "IdleHandler threw exception", t); }if (!keep) { synchronized (this) { mIdleHandlers.remove(idler); } } }// Reset the idle handler count to 0 so we do not run them again. pendingIdleHandlerCount = 0; // While calling an idle handler, a new message could have been delivered // so go back and look again for a pending message without waiting. nextPollTimeoutMillis = 0; } }

  • next中使用的是无限循环,如果队列中没有消息,就会一直阻塞在这里,如果有消息,就会返回这条消息给Looper进行处理,并且删除队列中的这一条消息。
ThreadLocal概述:
  • 当我们需要以线程为作用域,并且不同的线程具有不同的数据副本的时候,我们可以考虑使用这个类。我们以Handler举例,在Handler的构造方法中,想要获取当前线程的Looper, 而且不同的线程的Looper不是同一个,这个时候使用ThreadLocal就可以轻而易举的实现存取Looper的功能。
ThreadLocal使用
  • 我们下面通过一个例子来看看ThreadLocal的神奇之处, 测试代码如下:
    public class ThreadLocalTest { private static ThreadLocal mThreadLocal = new ThreadLocal<>(); public static void main(String[] args) { mThreadLocal.set("main"); System.out.println("main value:" + mThreadLocal.get()); new Thread(new Runnable() {@Override public void run() { // TODO Auto-generated method stub mThreadLocal.set("thread1"); System.out.println("thread1 value:" + mThreadLocal.get()); } }).start(); new Thread(new Runnable() {@Override public void run() { // TODO Auto-generated method stub mThreadLocal.set("thread2"); System.out.println("thread2 value:" + mThreadLocal.get()); } }).start(); } }

  • 测试结果如下:
    main value:main thread1 value:thread1 thread2 value:thread2

  • 通过结果我们看到了,我们虽然使用的是同一个mThreadLocal对象,但是在主线程和各个子线程中获取的值却是不一样的。这是因为当调用get方法的时候,首先会获取当前的线程中的ThreadLocalMap,它是一个以ThreadLocal自身为key, 要存储的值为value的一个可以理解为Map的东西, 实际上是一个数组,因为我们存储的时候是用不同的线程中的ThreadLocalMap进行存储的, 所以获取的值在不同的线程中自然也不一样,所以就互相不影响。我们下面从源码的getset来分析一下ThreadLocal
    public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }ThreadLocalMap getMap(Thread t) { return t.threadLocals; }void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }

  • 我们看到set方法是首先获取当前的线程,然后调用一个getMap(t)并且把获取的线程传入进去,这时候返回的是t.threadLocalst.threadLocalsThread中的定义是ThreadLocal.ThreadLocalMap threadLocals = null, 其实就是一个ThreadLocal.ThreadLocalMap,然后就以ThreadLocal自身为key, 把值存入到线程所在的ThreadLocalMap。下面我们看获取的逻辑:
    public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); }

  • 我们看到也是先获取当前的线程,然后获取当前的线程的ThreadLocalMap, 然后以ThreadLocalMapkey, 获取之前存入的值,这样每个线程获取的值只和当前线程有关,这就是ThreadLocal的神奇之处。ThreadLocal主要使用在Looper中, 下面我看关于Looper源码的分析。
Looper
  • Looper主要有两个主要方法分别是prepare()和loop(),首先看Looper.prepare()方法。
    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)); }

  • 【源码分析|Android Handler(手把手带你深入分析 Handler机制源码)】prepare中看到使用到了我们上面提到的ThreadLocal对象。首先判断了sThreadLocal.get()是否为空,如果为空的话就抛出异常,这里说明prepare()方法只能被调用一次。如果为空的话就存储当前线程的Looper到ThreadLocal中。然后进入Looper的构造方法中。
    private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }

  • 在构造方法中我们看到会创建一个MessageQueue。这个MessageQueue是Looper的成员变量,在Handler的构方法中,我们获取到了Looper之后,通过Looper就可以获取到Looper所持有的MessageQueue。
  • 下面看Looper中另一个重要的方法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 final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); }final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { //-----1----- msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } }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(); } }

  • 这个looper()方法是Handler机制中处理消息的方法,从for (; ; )看出,它会进入一个无限的循环,从消息队列MessageQueue中调用queue.next()获取消息, 如果队列中没有消息,线程就会阻塞; 当通过handler.sendMessage(Message msg)有新消息的时候, 调用的是queue.enqueue方法,会将Message添加到队列中,并且判断是否需要唤醒线程。
  • 在注释1处我们看到调用了msg.target.dispatchMessage(msg)来处理消息,查看Message源码知道这里的target其实就是Handler。下面我们来分析Handler的源码部分。
Handler
  • 我们使用Handler都是通过new出来的,我们自然直接看它的构造方法。Handler的构造方法主要分类两大类,一种是不设置Looper, 一种是设置Looper的。
  • 如果我们在构造方法中不传入Looper的话,最终源码如下:
    public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class 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 that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }

  • 如果我们在构造方法中传入Looper的话,最终源码如下:
    public Handler(Looper looper, Callback callback, boolean async) { mLooper = looper; mQueue = looper.mQueue; mCallback = callback; mAsynchronous = async; }

  • 从上面两种构造方法中看出,主要是关于Looper的处理;如果构造方法中没有传入Looper, 在前面Looper的源码部分提到,我们可以通过Looper.myLooper()来获取当前线程的looper, 如果这个Handler是在主线程创建的,那么我们获取到的looper, 其实就是在ActivityThread.main中通过Looper.prepareMainLooper()创建的,所以我们不需要手动调用Looper.prepare()创建。如果这个Handler是在子线程创建的,那么我们获取到的looper就为null, 就会抛出一个异常"Can't create handler inside thread that has not called Looper.prepare()")。所以我们在子线程中使用Handler的时候一定要记得调用Looper.prepare()去创建Looper(可以参考HandlerThread源码学习)。
  • 然后将Looper持有的MessageQueue赋值为Handler中的成员变量。
  • Handler中发送消息的方法有很多,最常用的是handler.sendEmptyMessage(msg), 但是最终都进入到的是sendMessageAtTime方法,下面我们通过源码看下。
    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); }

  • 最终调用了queue.enqueueMessage将消息加入MessageQueue中。加入到消息队列中,而Looper.loop()方法回不停的从队列中取出消息,调用msg.target.dispatchMessage(msg)来处理消息,前面我们知道实际调用的是handler.dispatchMessage(msg),我们通过源码来看下这个方法:
    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(); }

  • 首先会判断msg.callback != null, 这里这个callback其实是通过handler.post(runnable)发送的一个runnable, 如果不为null的话就执行handleCallback(msg),这个方法看上面的源码,其实就是执行runnbale中的代码而已。
  • 然后,如果mCallback != null就会执行mCallback.handleMessage(msg)中的逻辑,这个mCallback其实是其中一种构建Handler的构造方法中的参数,Handler handler = new Handler(callback)
  • 接着就调用了handleMessage 来处理,这个方法是需要我们重写的方法,里面根据Message处理我们的逻辑。
小结
  • 总的来说,首先是通过Looper.prepare方法将新建的looper存储在ThreadLocal中,并且在Looper的构造方法中创建一个MessageQueue。然后创建Handler实例,在Handler的构造方法中获取当前线程的looper以及通过looper获取到MessageQueue。再然后就调用Looper.loop()方法开始无限循环MessageQueue,等待有消息就处理。接着通过handler.sendMessage发送消息,将消息加入MessageQueue中,而looper这时候收到新来的消息时候,就会调用handler.dispatchMessage(msg)进行消息处理。
  • 那是如何切换线程的呢? 我们举例子线程发送消息到主线程,Handler是在主线程创建的,我们知道主线程的LooperActivityThread.main中就创建了,接着调用Looper.loop()方法,这个方法是在主线程无限循环处理消息的,如果我们从子线程发送一个Message, 这时候主线程在Looper.loop()方法中通过queue.next()获取的Message会通过msg.target.dispatchMessage(msg),也就是handler.dispatchMessage(msg)来处理消息,而这个dispatchMessage就是在主线程中执行的,最终实现了线程的切换。

    推荐阅读