Android中的消息机制(MessageQueue, Looper, Handler)总结

本文最先发布在简书
简书地址:http://www.jianshu.com/p/1f1163f54aa7

背景

    最近在使用Handler,想搞清楚他的原理,在网上看了好几篇文章都看的云里雾里的,直到看到了任玉刚老师的文章我才有了“啊,原来是这样!”的感觉。他的博客一再提分享精神,对我感触很大。所以决定把自己对Handler的想法给大家分享一下, 哪里有不对的地方联系我, 我们一起探讨一起进步。

前言

    我们大家都知道Android为了满足线程间的通信为我们提供了Looper和Handler。相信大家也都知道Handler怎么使用,可是Handler为什么要这么用呢?什么原理呢?今天不讨论他怎么用,我们来分析一下他的工作流程。如果坚持读到最后,相信你一定会有所收获的(ps:哪位小伙伴不了解用法可以留言,空闲下来我会写一篇用法供你了解)

正文

消息机制的工作流程:

  我们先来看一下他的流程图

消息机制
    最开始先由执行任务的线程通过Handler发送消息即去向MessageQueu(消息队列)去插入一条消息,然后Looper从MessageQueue中不断地循环来取出消息,经由Looper处理最终将他交给了Hanlder,这样最终就由Handler所在的线程来处理这条消息了。想必大家还是不太清楚,让我们接下来详细的分析一下每个步骤。

MessageQueue(消息队列)

    我们先来看一下他的源码

public final class MessageQueue {
              .....
     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 {
                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;
    }
                  .....
     Message next() {

        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;
                }
                if (mQuitting) {
                    dispose();
                    return null;
                }
                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);
            }

            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);
                    }
                }
            }
            pendingIdleHandlerCount = 0;
            nextPollTimeoutMillis = 0;
        }
    }
}

    代码比较长,大家不用深究,看代码我们不难发现实际上他就是一个链表。通过enqueueMessage()方法来插入消息,通过next()来返回并移除消息,这就是MessageQueue的工作原理,让我们先记住这两个方法的名字。

Looper

    我们还是先来看一下代码在做解释

public final class Looper {
              ......
   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));
    }
}

    先来看一下他的prepare()方法,首先他先做了一个判断,如果已经存在了Looper他就会抛出

throw new RuntimeException("Only one Looper may be created per thread");

    这也就是为什么一个线程只能存在一个Looper的原因。让我们继续向下看

public final class Looper {
              ......
   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;

        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {

            Message msg = queue.next(); // 注意这里!!!

            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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);  //注意这里!!!

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

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


}

    从代码我们可以看出内部就是一个无限循环,不断地调用MessageQueue的next()方法来取出消息,没错就是之前让你记住MessageQueue中的两个方法之一。最后执行这行代码

msg.target.dispatchMessage(msg); //注意这里!!!

这里的msg.target就是我们所说的Handler(),没错,就是在这里将我们的消息最终交给了Handler。也许你会说:你说是就是啊我们怎么知道你有没有骗我。

public final class Message implements Parcelable {
            ........
            Handler target;
            .......
}

    这回你信了吧。这里Looper你应该明白了,经过Looper的处理最终将消息交给了我们的Handler,让我们继续看Handler。

Handler

    我们先来看他的sendMessage().

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

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

 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);//注意这里!!!
    }

    经过sendMessage的层层调用,最后我们发现他调用了enqueueMessage(),也就是最开始我们记住的两个方法之一,就是向MessageQueue中插入消息。这也就是我们的发送阶段。我们还记得Looper最后调用了Handler的dispatchMessage(),他内部是什么机制呢,让我们来看一下。

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

  到了这里我相信大家一定不会陌生了吧,看到了我们最熟悉的handleMessage()了。这里就到了Handler对消息的处理阶段了, 现在我们就可以在Handler所在的线程做自己想做的处理了。

尾语

  到这里消息机制的流程我们已经梳理完了,各部分的原理相信你也有了一定的了解,相信你现在回过头去看前面的流程图已经有了不一样的感觉了。本人能力有限,只想分享一下自己的见解,希望我们一起进步,有什么疏漏一定要联系我哦!!!很乐意与你交流探讨!!!

注!!!

   总结不易,请尊重劳动成果,转载请标明出处,谢谢!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值