一张图让你明白Handler、Message、Looper消息机制

转载请注明出自flowsky37的博客,尊重他人辛苦劳动!

在android开发中,Handler太熟悉了,处处可见。确实挺好用的。它可以轻松的将任务切换到Handler所在的线程中去执行。如下面代码:

//发送message
MyHandler myHandler = new MyHandler(this);

        //业务逻辑
        ...
        Message message = new Message();
        message.what = 0x001;
        myHandler.sendMessage(message);
//接收message
public class MyHandler extends Handler {

    private Context context;

    public MyHandler(Context context) {
        this.context = context;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case 0x001:

                //业务逻辑
                //...

                Toast.makeText(context,"收到messge",Toast.LENGTH_SHORT).show();
                break;
            default:
                super.handleMessage(msg);
                break;
        }
    }
}

so easy,对吧!很多人认为Handler的作用是更新UI,这没问题。但是更新UI只是Handler的一个特殊使用场景。具体来讲,所有比较耗时的操作一般都是在子线程中完成,否则容易引起ANR,如读写文件、数据插入、网络请求等,完成后需要对UI进行修改的,但是由于android开发规范限制,子线程不能更新UI。所以这时候通过Handler将更新UI的操作切换到主线程中执行。通俗的讲,Handler不是为了UI而生,只是常被大家用来更新UI。Handler的主要作用应该是将一个任务切换到某个指定的线程中去执行。

Android的消息机制主要是指Handler运行机制,关于Handler运行机制,我们不得不提到其底层的MessageQueue与Looper。其关系大概如下图:
一张图让你明白Handler、Message、Looper消息机制_第1张图片

没看懂?没关系,后面会更详细的。先说一下MessageQueue与Looper是啥呢!

MessageQueue:消息队列,它内部存储了一组消息,以队列的形式对外提供插入和删除的工作。内部结构不是真正的队列,而是采用单链表的数据结构来存储消息列表。

Looper:可以理解为消息循环。MessageQueue 只是一个消息的存储单元,它不能去处理消息,Looper 填补了这个功能,Looper 会以无限循环的模式去查看Message中是否有新消息,否则就一直等待。

重点:如果需要使用Handler就必须为当前线程创建一个Looper,因为线程默认是没有Looper的。如果线程中没有Looper的话,会抛出异常的。我我们可以一起看看一下Handler的构造源码,它有好几个构造函数:


    /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }

无参数的,接着往下看:

/**
     * Constructor associates this handler with the {@link Looper} for the
     * current thread and takes a callback interface in which you can handle messages.
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler(Callback callback) {
        this(callback, false);
    }

还有好几个其它的构造方法,可自行阅读源码。这两个构造方法都指向了this(callback, false),我们接着看this(callback, false)的具体实现:


    public Handler(Callback callback, boolean async) {

         ...

        //获取当前线程的looper对象 
        mLooper = Looper.myLooper();
        //判断Looper是否为null
        if (mLooper == null) {
        //如果为null则报异常
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

通过源码可以看出,在创建Handler实例的时候,先会通过Looper.myLooper()去获取当前线程的Looper,然后判断looper是否为null。如果为null,会提示通过Looper.prepare()去创建。
我们接着看下Looper.prepare()的源码:

 /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    public static void prepare() {
        prepare(true);
    }

prepare()是一个空构造函数,其内部是调用了prepare(true),我们接着看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));
    }

最后一行代码很很清楚的显示了创建了一个Looper对象。先判断当前线程时候是否有Looper,如果有的话就会抛异常提示每个线程只能有一个Looper,没有的话则创建。

子线程中Handler的初始化Looper的代码:

new Thread("Thread#1"){
            @Override
            public void run() {
                //初始化Looper对象
                Looper.prepare();
                Handler handler = new Handler();
                //开启消息循环
                Looper.loop();
            }
        }.start();

细心的同学可能发现了,怎么最开始的示例代码中没有见着去调用 Looper.prepare()创建Looper对象啊!

其实UI线程,也就是ActivityThread,在被创建时就会初始化Looper,这也是我们在主线程中不需要调用Looper.prepare()能直接使用Handler的原因。

Handler创建完毕后,可以通过send方法发送消息,也可以通过post将一个Runnable对象投递到Looper中去处理。看一下post方式源码:

 /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 

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

我们其实会发先post本质上也是同过send方式来完成的。Handler通过send方式发送消息,它会调用调用MessageQueue中的enqueueMessage方法将消息插入到队列中,然后Looper调用MessageQueue中next方法发现有新的消息来了,就开始处理这个消息,然后消息中的Runnable或者Handler中的handleMessage就会被调用处理消息。这样子消息就从子线程切换到了主线程中。大概流程如下图所示:

一张图让你明白Handler、Message、Looper消息机制_第2张图片

Handler中send方式发送消息的方法有三种:

  • sendMessage(Message msg)
  • sendMessageDelayed(Message msg, long delayMillis )
  • sendMessageAtTime(message msg , long uptimeMillis)。

具体用法就不说了,看方法命名就能知道。我们进一步看看其源码,首先是sendMessage(Message msg):

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

很简单,调用了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);
    }

可以看到在其方法内部,先获取了消息队列,然后判断是否为null,接着调用了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中enqueueMessage方法内部调用了MessageQueue中的enqueueMessage方法,虽然方法名一样,却是两个不同类中的不同方法。

MessageQueue即Handler中的消息队列,主要包含两个操作:插入和读取。分别对应的方法是:

  • enqueueMessage
  • next

其中enqueueMessage作用是往消息队列中插入一条消息,而next的作用是从消息队列中取出一条消息并将其从消息队列中移除。

继续看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尽管叫消息队列,但是它的内部是通过一个单链表的数据结构来维护消息列表,单链表在插入和删除上比较有优势。

我们接着看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,接着我们来看Looper:

Looper 在消息机制中作用是消息循环,它会不停的从MessageQueue中查看时候有新消息到达,如果有新消息会立刻处理,如果没有新消息,则一直阻塞在哪里。

Looper中最重要的一个方法是loop,只有调用了loop后,消息循环才真正的开始工作。查看其源码:

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the 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 {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            ...


        }
    }

首先是通过myLooper()获取当前线程的Looper对象,接着获取消息队列。继续往下我们有看了一个无限循环,当没有消息存在时,queue.next()就会一直阻塞在这里。接着往下看,当有消息存在时,msg.target.dispatchMessage(msg)就会处理消息。msg.target是什么呢?在前面我们分析的Handler中enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)源码中我们可以看到:

msg.target = this;

即msg.target就是Handler对象,这样消息从Handler发出,最后又交给自己的dispatchMessage处理了,这里dispatchMessage方法是在创建Handler时所使用的Looper中执行。这样就成功的将代码逻辑切换到指定的线程中去执行了。

MessageQueue与Looper的分析到这里基本结束了。

我们接着回到Handler中dispatchMessage方法:

 /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

我们接着分析,先判断msg.callback是否为空,否则调用handleCallback(msg)方法。那msg.callback是什么呢?在前面我们说了Handler的发送消息有post和send两种方式。看下post方式源码:

 /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 
     */
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

很简单,接着看看getPostMessage(r):

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

OK,终于找到m.callbac了,其实就是Handler的post方法中所传递的Runnable参数。我们回到dispatchMessage方法继续,当Runnable对象不为null时,调用handleCallback方法:

private static void handleCallback(Message message) {
        message.callback.run();
    }

是不是一下子很清楚了,就是Runnable中的run()方法。我们接着看,然后是判断mCallback是否为null,不为null则调用handleMessage()方法。Callback其实是一个接口:

 /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

那么这个Callback是什么时候传入的呢?前面我们有说过,Handler的构造方法有好几个,我们看看其中的另几个:

/**
     * Constructor associates this handler with the {@link Looper} for the
     * current thread and takes a callback interface in which you can handle
     * messages.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     *
     * @param callback The callback interface in which to handle messages, or null.
     */
    public Handler(Callback callback) {
        this(callback, false);
    }
 /**
     * Use the provided {@link Looper} instead of the default one and take a callback
     * interface in which to handle messages.
     *
     * @param looper The looper, must not be null.
     * @param callback The callback interface in which to handle messages, or null.
     */
    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }
    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

一下清晰了,Callback可以作为构造函数的参数传入。我们接着看,当mCallback为null时,执行handleMessage(msg):

 /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

这个方法是不是异常熟悉,就是我们平常创建Handler时派生一个其子类并重写其handleMessage方法来处理具体的消息。同时,Callback给我们提供了另外一种可以不用派生子类使用Handler的方式。

到这里,Handler的源码分析基本结束!

有人可能大喊一声,说好的一张图就让我明白的Handler消息机制呢?coder与coder之间的信任在哪里?

好吧,综合上述,可以用这样的一张图来表示其相互之间的关系及调用逻辑:

一张图让你明白Handler、Message、Looper消息机制_第3张图片

图有点…我也很忧伤,大家放大了看看吧!将它们之间的联系描述得非常清晰

呃..然后对第一张图中出现的ThreadLocal说明一下,在获取Looper的prepare方法中,我们其实可以看到其实是通过ThreadLocal获取到的Looper对象。ThreadLocal是一个线程内部的数据存储类,它可以在不同的线程互不干扰的存储并提供数据。

基本上是这样子了。

如果有不明白的,可以留言;如果某些地方有误,非常欢迎指出,谢谢!

你可能感兴趣的:(android)