本文的目的是来分析一下Android系统中以Handler、Looper、MessageQueue组成的异步消息处理机制,经过源码来了解一下整个消息处理流程的走向以及相关三者之间的关系。app
须要先了解如下几个预备知识less
Handler发送消息的形式主要有如下几个形式,其最终调用的都是sendMessageAtTime()方法异步
public final boolean sendMessage(Message msg){ return sendMessageDelayed(msg,0); } public final boolean post(Runable r){ return sendMessageDelayed(getPostMessage(r),0); } public final boolean sendMessageDelayed(Message msg ,long delayMillis){ if(delayMillis<0){ delayMillis = 0 ; } return sendMessageAtTime(msg,SystemClock.uptimeMillis()+delayMillis); }
能够看到sendMessageAtTime()方法中须要一个已初始化的MessageQueue类型的全局变量mQueue,不然程序没法继续走下去async
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变量是在构造函数中进行初始化的,且mQueue是成员变量,这说明Handler与MessageQueue是一一对应的关系,不可更改ide
若是构造函数没有传入Looper函数,则会默认使用当前线程关联的Looper对象,mQueue须要依赖从Looper对象中获取, 若是Looper对象为null,则会直接抛出异常,且从异常信息 Can't create handler inside thread that has not called Looper.prepare() 中能够看到,在向 Handler 发送消息前,须要先调用 Looper.prepare()函数
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; mAsynchronous = async ; }
走进Looper类中,能够看到,myLooper()方法是从sThreadLocal 对象中获取Looper对象的,sThreadLocal对象又是经过prepare(boolean)来进行赋值的,且该方法只容许调用一次,一个线程只能建立一个Looper对象,不然将抛出异常oop
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); public static @Nullable Looper myLooper() { return sThreadLocal.get(); } 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(boolean)屡次调用会抛出异常致使没法关联多个Looper外,Looper类的构造函数也是私有的,且在构造函数中还初始化了一个线程常量mThread,这都说明了Looper只能关联到一个线程,且关联以后不能改变post
final Thread mThread; private Looper(boolean quitAllowed){ mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
那么Looper.prepare(boolean) 方法又是在哪里调用呢?查找该方法的全部引用,能够发如今Looper类中有以下方法, 从名字来看,能够猜想该方法是由主线程来调用的。 查找其引用ui
public static void prepareMainLooper(){ prepare(false); synchronized(Looper.class){ if(sMainLooper !=null){ throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
最后定位到ActivityThread 类的main()方法this
看到main()函数的方法签名, 能够知道该方法就是一个应用的起始点,即当应用启动时,系统就自动为咱们在主线程作好了Handler的初始化操做,所以在主线程里咱们能够直接使用Handler
若是是在子线程中建立Handler, 则须要咱们手动调用Looper.prepare()方法
public static void main(String[] args){ ... Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attch(flase); if(sMainThreadHandler == null){ sMainThreadHandler = thread.getHandler(); } if(false){ Looper.myLooper.setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } //End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
回到最开始, 既然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()"); } //获取 MessageQueue 对象 mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
mQueue 又是在Looper类的构造函数中初始化的, 且mQueue是Looper类的成员变量, 这说明Looper与MessageQueue是一一对应的关系
private Looper(boolean quitAllowed){ mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
sendMessgaeAtTime()方法中在处理Message时,最终调用的是enqueueMessage()方法
当中,须要注意msg.target = this 这句代码,target对象指向了发送消息的主体,即Handler对象自己,即由Handler对象发送MessageQueue 的消息最后仍是要交由Handler对象自己来处理
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) { //target 对象指向的也是发送消息的主体,即 Handler 对象 //即由 Handler 对象发给 MessageQueue 的消息最后仍是要交由 Handler 对象自己来处理 msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
由于存在多个线程往同一个Loop线程的MessageQueue中插入消息的可能, 因此enqueueMessgae()内部须要进行同步。能够看出MessageQueue内部是以链表的结构来存储Message的(Meassage.next),根据Message的延时时间的长短来将决定其在消息队列中的位置
mMessages表明的是消息队列中的第一条消息,若是mMessages为空, 说明消息队列是空的,或者mMessages的触发时间要比新消息晚,则将新消息插入消息队列的头部,若是mMessgaes不为空,则寻找消息队列中第一条触发时间比新消息晚 的非空消息,并将新消息插到该消息前面
到此,一个按照处理时间进行排序的消息队列就完成了,后边要作的就是从消息队列中依次取出消息进行处理了
boolean enqueueMessage(Message msg, long when) { //Message 必须有处理者 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中消息的读取实际上是经过内部的next()方法进行的,next()方法是一个无限循环的方法, 若是消息队列中没有消息,则该方法会一直阻塞,当有新消息来的时候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()方法又是经过Looper类的Loop()方法来循环调用的,而loop()方法也是一个无限循环,惟一跳出循环的条件就是queue.next()方法返回为null, loop()方法就是在ActiityThread的main()函数中调用的
由于next()方法是一个阻塞操做, 因此当没有消息也会致使loop()方法一直阻塞着,而当MessageQueue中有了新的消息,Looper就会及时处理这条消息并调用Message.target.dispatchMessage(Message) 方法将消息传回给 Handler 进行处理
/** * 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); } } 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(); } }
看下Handler对象处理消息的方法
/** * Handler 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 不为空,则调用callback对象的run()方法,该callback实际上就是一个Runnable对象,对应的是Handler对象的post()方法
private static void handleCallback(Message message){ message.callback.run(); } 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 ; }
若是mCallback 不为null ,则经过该接口来回调处理消息, 若是在初始化Handler对象时没有经过构造函数传入Callback回调接口, 则交由handleMessage(Message)方法来处理消息,咱们通常也是经过重写Handler的hanleMessage(Message)方法来处理消息
最后来总结下以上的内容
1、在建立Handler实列时要么为构造函数提供一个Looper实列,要么默认使用当前线程关联的Looper对象,若是当前线程没有关联的Looper对象,则会致使抛出异常
2、Looper与Thread ,Looper与MessageQueue都是一一对应的关系, 在关联后没法更改,但Handler 与Looper能够是多对一的关系
3、Handler能用于更新UI有个前提条件:Handler与主线程关联在了一块儿。 在主线程中初始化的Handler会默认与主线程绑定在一块儿, 因此此后在处理Message时,handleMessage(Message msg)方法的所在线程就是主线程,由于Handler能用于更新UI
4、能够建立关联到另外一个线程Looper的Handler,只要本线程可以拿到另一个线程的Looper实列
new Thread("Thread_1") { @Override public void run() { Looper.prepare(); final Looper looper = Looper.myLooper(); new Thread("Thread_2") { @Override public void run() { Handler handler = new Handler(looper); handler.post(new Runnable() { @Override public void run() { //输出结果是:Thread_1 Log.e(TAG, Thread.currentThread().getName()); } }); } }.start(); Looper.loop(); } }.start();