android Handler Looper MessageQueue 深入解析

659 阅读7分钟

Handler:主要负责消息的发送和接受;
Looper: 在android的消息机制中扮演着消息循环的角色;
MessageQueue:消息存放的容器;
下面我们就按照消息发送的流程 通过源码解析进一步了解 Handler、Looper、MessageQueue 这三者之间的关系。

Handler 的消息发送可以通过send或者post 方法来实现。
post:

 public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

send:

 public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

通过上述代码我们可以看到 无论是post 还是send 最终都是调用了
sendMessageDelayed 该方法,所以我们只需要通过该方法进行研究即可。

以下是 sendMessageDelayed 方法的源码

 public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

可以看到该方法中调用了 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);
    }

在该方法中我们可以看到 mQueue 是一个全局变量,而这个变量的赋值是在Handler 构造函数中得到的。
同时在Handler 构造函数中 我们可以看到mQueue变量的获取依赖于Looper 对象是否为空。如果Looper对象为空,则程序将抛出异常,Can’t create handler inside thread that has not called Looper.prepare() ,通过改异常我们可以看出在使用Handler.sendMessage之前,我们必须调用Looper.prepare()该方法去初始化Looper对象,

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

那么现在又读者疑问了,我们在UI 线程中并没有去调用Looper.prepare()方法,那么这是为什么呢?
以下将会结束为什么主线程中没有调用Looper.prepare()方法:
首先我们先看ActivityThread的main函数:


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

        ....


        Looper.loop();

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

我们都知道Activity启动之后会启动主线程ActivityThread ,在ActivityThread main 函数中我们可以看出内部调用了
Looper.prepareMainLooper();

public static void prepareMainLooper() {
        prepare(false);
        ....
    }

而 Looper.prepareMainLooper() 该方法在Looper中调用了prepare方法,

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

该方法中 初始化了一个Looper对象并将该对象放在了ThreadLocal对象中。

可以看出主线程也必须调用Looper.prepare()该方法,只不过系统已经帮我们初始化了,不需要我们去主动调用了。

而在非主线程中,我们必须手动调用Looper.prepare()方法。

==============================

当Looper 不为空 则从Looper对象中得到了 mQueue

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 
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

通过mQueue是通过Looper 中的一个属相变量得到了,那么我们可以猜测mQueue的初始化时在Looper中 进行初始化的。

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

果不出所料 在Looper 的构造函数中我们看到了 mQueue的初始化 其实 mQueue 是一个MessageQueue对象。

ok 现在我们继续看Handler的消息发送,在sendMessageAtTime 方法中得到mQueue对象之后,调用了 enqueueMessage该方法,

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

通过改方法 我们可以看出最终调用了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;
    }

我们通过源码可以看出 MessageQueue 内部的存储是通过单链表的形式 存储Message的。
同时Handler发送消息其实就是往MessageQueue中插入了一条message。

ok 到现在我们应该能明白消息是如何通过Handler对象进行发送的。

下面我们继续看消息是如何从MessageQueue 中读取出来,然后回调给Handler的。

在MessageQueue中 消息的读取其实是通过内部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 handler

                boolean 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 方法是一个无限循环的方法,如果消息队列中没有消息,则next方法一直阻塞在这里,当有新消息来的时候next方法会返回这条消息并将其从单链表中删除。

而MessageQueue.next() 方法 我们可以看出 是在 Looper.loop

   public static void loop() {
        final Looper me = myLooper();
          .....
        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);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            .....
    }

通过Looper.loop源码我们可以看到,loop方法也是一个无线循环,唯一跳出循环条件是 queue.next() 返回为null
而next 方法是一个阻塞操作,当没有消息时,next一直阻塞在哪,这也导致loop 一只阻塞在哪。
如果messageQueue 中有 了新的消息,Looper就会处理这条消息。 调用msg.target.dispatchMessage(msg); 该方法。
通过源码

 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

这样Handler发送的消息最终又交给了Handler的dispatchMessage 方法
而Handler 的dispatchMessage方法源码

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

首先 检查Message的callback 是否为null, 不为null 就通过handleCallback 来处理消息,Message的callback是一个Runnable对象,实际上就是 Handler的post方法所传递的Runnable参数

通过源码可以看到


 public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }
private static void handleCallback(Message message) {
        message.callback.run();
    }

通过handleCallback 源码可以看出 回调到了 外部Runnable 的 run方法;

外部使用:

 handler.post(new Runnable() {
            @Override
            public void run() {

            }
        });

如果message.callback 为null,则会继续去判断 mCallback 是否为null;
如果不为null,则调用mCallback.handleMessage(msg) 该方法,

mCallback.handleMessage(msg)的源码 可以看出

  public interface Callback {
        public boolean handleMessage(Message msg);
    }

由此 我们可以看出 外部Handler 可以通过 Callback 来创建

外部使用:

  Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

当 mCallback 为null 则直接调用 handleMessage(msg); 该方法

外部使用;

private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }; 

以下是dispatchMessage 的调用流程图

这里写图片描述

ok 到这我们还存在一个疑问,就是Looper.loop是什么时候调用的?

通过ActivityThread 的源码我们可以看出

 public static void main(String[] args) {
        ....
        Looper.loop();
        ....
    }

在主线程中系统是帮助我们调用了Looper.loop方法,所以在非主线程中我们需要手动去调用Looper.loop 方法。