Handler消息机制

454 阅读7分钟

Handler是用来发送和处理MessageRunnable的,每个Handler实例都是与一个线程和该线程的消息队列相关联的,如果当前线程没有创建Looper有可能会抛异常。有可能的意思是有两种情况:

  • 当前线程没有创建Looper,直接调用无参构造Handler()则会抛异常;
  • 当前线程没有创建Looper,调用Looper.loop()则会抛异常。

创建Handler、Looper和MessageQueue

    public Handler() {
        this(null, false);
    }
    public Handler(Callback callback) {
        this(callback, false);
    }

这两个构造器都是在当前线程创建Handler,我们通常会使用第一个方法创建Handler;第二个是设置一个处理MessageCallback接口。

    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;
        //是否异步,默认false
        mAsynchronous = async;
    }

上面两个构造器最终都会执行这个构造器,mLooper是使用Looper.myLooper()赋值的,如果为空会抛出RuntimeException,然后将LoopermQueue赋值给HandlermQueuemQueue就是消息队列。再看一下Looper.myLooper()

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

可以看到Looper是通过ThreadLocal<Looper> sThreadLocal获取到的,这里先介绍一下ThreadLocal的两个主要方法,过多细节不介绍:

    public void set(T value) {
        //获取当前线程
        Thread t = Thread.currentThread();
        //根据t获取ThreadLocalMap,key是ThreadLocal类型
        ThreadLocalMap map = getMap(t);
        if (map != null)
            //如果map不为空,直接设置
            map.set(this, value);
        else
            //如果map为空,创建新的map,再把value放进去,本篇放的值是Looper对象
            createMap(t, value);
    }
    
    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();
    }

上面代码挺简单的就不做解释了,具体介绍一下 ThreadLocal: 这个类提供线程局部变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 话又说回来,那么什么时候把Looper设置到ThreadLocal<Looper> sThreadLocal里的?其实是在app启动的时候就设置了,下面是ActivityThreadmain方法:

    public static void main(String[] args) {
        ...

        Looper.prepareMainLooper();

        ...
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

这里调用了Looper.prepareMainLooper(),然后又会调用prepare(false),创建新的Looper,并将它设置到sThreadLocal里。这里主线程的Looper就创建完成了,接着调用Looper.loop()开始轮询,这个后面再讲。

    public static void prepareMainLooper() {
        //主线程Looper不允许退出
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                //因为一个线程只能有一个Looper
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    
    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //将新的Looper设置到ThreadLocal里
        sThreadLocal.set(new Looper(quitAllowed));
    }
    
    private Looper(boolean quitAllowed) {
        //创建消息队列
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

这里注意一下上面的quitAllowed参数,这个参数在主线程里是false,表示Looper不允许退出,否则抛出IllegalStateException("Main thread not allowed to quit.")。到了这里,主线程创建LooperHandlerMessageQueue就介绍完了。

    public Handler(Looper looper) {
        this(looper, null, false);
    }
    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }

这两个构造器可以在任意线程创建Handler,主线程使用Looper.myLooper(),子线程使用Looper.prepare()

    public static void prepare() {
        //这里的quitAllowed参数是true,表示Looper允许退出
        prepare(true);
    }
    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

这里比较简单就是进行赋值,创建完不要忘记调用Looper.loop()开始轮询。注意:不使用时要调用Looper.quit()Looper.quitSafely(),前者是移除消息队列中所有消息,后者是移除未触发的消息。否则Looper会处于等待状态。

发送消息

    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);
    }
    
        public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }

无论调用哪一种发送消息的方法都会走到这两个方法,只是第二个方法的uptimeMillis为0,表示需要立即执行。下面看一下enqueueMessage:

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

这里注意msg.target就是Handler,然后交给MessageQueueenqueueMessage插入消息队列。

插入消息

    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            //如果Handler为空抛出异常
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            //消息已经被使用
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            //只有调用Looper.quit()时为true
            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) {
                // 当前消息队列为空或when == 0或运行时间小于p的运行时间就插入到头部.
                msg.next = p;
                mMessages = msg;
                //needWake需要根据mBlocked的情况考虑是否触发
                needWake = mBlocked;
            } else {
                //当前消息队列不为空,并且不需要立即运行,并且当前运行时间>=p的运行时间
                //插入队列中间,我们不必唤醒事件队列,除非队列头部存在障碍并且消息是队列中最早的异步消息。
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                //开始循环直到当前消息为空,或者运行时间小于p的运行时间
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        //因为消息队列之前还剩余消息,所以这里不用调用nativeWakeup
                        needWake = false;
                    }
                }
                // 将msg按照时间顺序插入消息队列,p - msg - next
                msg.next = p; 
                prev.next = msg;
            }
            if (needWake) {
                //调用nativeWake,以触发nativePollOnce函数结束等待
                nativeWake(mPtr);
            }
        }
        return true;
    }

MessageQueue是按照Message触发时间的先后顺序排列的,队头的消息是将要最早触发的消息。当有消息需要加入消息队列时,会从队列头开始遍历,直到找到消息应该插入的合适位置,以保证所有消息的时间顺序。那么插入到队列中的消息是如何取出来的呢?当然是Looper.loop()啦,

取出消息

    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            //如果当前线程没有Looper抛出异常
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        ...

        for (;;) {
            // 通过next方法取出消息,这里是关键,我们后面分析,先说一点next没有消息会一直处于阻塞状态,
            // 所以不会往下走
            Message msg = queue.next();
            if (msg == null) {
                // 没有消息表明消息队列正在退出。
                return;
            }
            ...
            //分发取出的消息,这里msg.target就是Handler
            msg.target.dispatchMessage(msg);
            ...
            //处理过之后要把消息回收
            msg.recycleUnchecked();
        }
    }

接下来我们去看看MessageQueuenext()

    Message next() {
        // 如果消息队列执行了quit或dispose就会返回空的消息
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // 循环迭代的首次为-1
        //如果为-1,则表示无限等待,直到有事件发生为止。如果值为0,则无需等待立即返回
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //阻塞操作,当到了nextPollTimeoutMillis时长,或者消息队列被唤醒,都会返回
            //这里底层做了大量的工作,水平有限就不细究了
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // 尝试检索下一条消息, 如果找到则返回。
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    //当消息Handler为空时,查询MessageQueue中的下一条异步消息msg并退出循环。
                    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 {
                        // 获取一个消息并返回,把msg.next设置成当前消息.
                        //如果取到了消息mBlocked为false,没取到就是
                        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的使用状态
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // 没有找到消息.
                    nextPollTimeoutMillis = -1;
                }

                // 如果消息正在推出,返回null.
                if (mQuitting) {
                    dispose();
                    return null;
                }

              if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    //第一次迭代,并且消息队列为空或者是第一个消息
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // 没有 idle handlers 需要执行.  处于等待状态并跳过这次迭代.
                    mBlocked = true;
                    continue;
                }
            
            ...

            //重置idle handler个数为0,以保证不会再次重复运行
            pendingIdleHandlerCount = 0;
            //当调用一个空闲handler时,一个新message能够被分发,因此无需等待可以直接查询pending message.
            nextPollTimeoutMillis = 0;
        }
    }

这样消息就被取出来了,接下来看看是如何处理消息的。

处理消息

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

如果msgcallback不为空,则执行handleCallback(msg);否则看HandlermCallback是否为空,不为空则执行mCallback.handleMessage(msg),若mCallback.handleMessage(msg)返回true则直接退出方法,否则执行handleMessage(msg)handleMessage(msg)是个空方法,需要我们自己来实现。