它高傲,但是宅心仁厚,它低调,但是受万人景仰。他可以把神赐给人类的android,贯穿得出神入化,使用堪称之艺术的回调方式。他究竟是神仙的化身?还是地狱的使者?没人知道,但是可以肯定,每个人都给他一个称号——Handler!
handler是android开发中提到频率比较高的词。那它到底是何方神圣?一切对象都可以归结为三个哲学问题:它是谁?它能干嘛?它是怎么实现的?
-
它是谁?
Handler允许你发送和处理Message和Runnable对象。每一个Handler实例与单一线程和该线程的message queue相关联。当创建一个Handler实例的时候,它就和它所在的线程、该线程所对应的消息队列绑定在了一起,这时它就可以把消息或者runnable对象提交到消息队列中,并在取出消息队列时处理它们。 -
它能干嘛?
Handler主要有两个用途:(1)调度Message和runnable对象在将来某个时间点被执行。(2)在自己的线程里队列一个action以执行。
handler调度message通过post(Runnable r),postAtTime(Runnable r, long uptimeMillis),postAtTime(Runnable r, Object token, long uptimeMillis),postDelayed(Runnable r, long delayMillis)和sendMessage(Message msg),sendEmptyMessage(int what),sendEmptyMessageDelayed(int what, long delayMillis),sendEmptyMessageAtTime(int what, long uptimeMillis),sendMessageDelayed(Message msg, long delayMillis),sendMessageAtTime(Message msg, long uptimeMillis)等方法来完成。其中post开头的方法,用于把runnable对象加入消息队列中(实际上消息列队只接受Message对象的加入,这里实质上是把runnable对象封装成Message再添加到消息队列中,后面的源码分析会清楚地看到),并在取出时执行。而send开头的方法,用于把Message对象提交到消息列队中,Message对象可以携带Bundle数据,在取出消息列队时在handler的handleMessage(Message msg)方法中处理(该方法需要重写)。
当应用启动的时候,主线程就创建了一个专用的消息列队,用于处理和应用级别有关的,比如Activity、broadcast,receivers等,这时我们可以创建自己的线程,并通过handler来用于线程间的交流。
-
它是怎么实现的?
创建Handler实例时,通过其创建时所在的线程获取得到与该线程绑定的Looper对象,并把获取到的Looper对象和Looper对象下的成员变量Message Queue分别赋值给自己的成员变量,自此handler就和消息队列关联上了。请看代码:
public Handler() { this(null, false); }
无参构造方法调用的这个有参构造方法:
看红色代码,Looper.myLooper()返回与该线程绑定的looper实例,别问我怎么知道=.=这我们就去看看这个方法怎么实现以求真相~!打开Looper源码,找到myLooper方法:public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } <span style="color:#FF0000;"><strong>mLooper = Looper.myLooper();</strong></span> if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } <span style="color:#FF0000;"><strong>mQueue = mLooper.mQueue;</strong></span> mCallback = callback; mAsynchronous = async; }
只有一行代码~!看源码的时候会经常看到这样很简洁的方法体~谷歌工程师就是这么吊~!从sThreadLocal对象中取出looper返回当前线程绑定的looper,那么sThreadLocal又是何方神圣?/** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ public static Looper myLooper() { <strong><span style="color:#FF0000;"> return sThreadLocal.get();</span></strong> }
可以看到sThreadLocal是ThreadLocal类的实例,那么这个类又是什么?另外注意标注红色注释:当调用prepare()方法后,sThreadLocal.get()方法取到的才不为空。//<span style="color:#FF0000;"> sThreadLocal.get() will return null unless you've called prepare().</span> static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
看类介绍可知,该类用于给每一个线程存取取一个值,所有的线程共享该类的实例,每个线程可以访问它取出绑定的值,这个值可以为空。看看其get方法是怎么实现的:/** * Implements a thread-local storage, that is, a variable for which each thread * has its own value. All threads share the same {@code ThreadLocal} object, * but each sees a different value when accessing it, and changes made by one * thread do not affect the other threads. The implementation supports * {@code null} values. * * @see java.lang.Thread * @author Bob Lee */
嗯,首先获得获得当前线程,并通过当前线程作为key取出与之绑定的values!那问题来了,那么它是怎么把looper和线程绑定到一起呢?先看看它set方法的实现:public T get() { // Optimized for the fast path. Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values != null) { Object[] table = values.table; int index = hash & values.mask; if (this.reference == table[index]) { return (T) table[index + 1]; } } else { values = initializeValues(currentThread); } return (T) values.getAfterMiss(this); }
先获取当前线程,然后把线程和传进来的值绑定在一起~!现在我们回到上面红色标注的地方,嗯,我们现在就去看看prepare()方法是怎么实现的:public void set(T value) { Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values == null) { values = initializeValues(currentThread); } values.put(this, value); }
prepare()方法里调用了prepare(boolean quitAllowed)方法,所以把两个方法放在一起便于一目了然。在prepare(boolean quitAllowed)中我们可以看到其先判断当前线程是否绑定有looper对象,如果有将抛出异常,因为每个线程只能对应于一个looper对象。然后创建一个looper实例并和当前线程绑定在了一起。那么消息队列呢?不急,我们这就去看看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"); } <strong><span style="color:#FF0000;">sThreadLocal.set(new Looper(quitAllowed));</span></strong> }
嗯,looper创建的时候,就创建了一个消息队列赋值给自己的成员变量mQueue并获取当前线程同样赋值给自己的成员变量mThread。到此,我们就清晰了,handler包含一个looper对象和MessageQueue对象,looper对象包含一个MessageQueue对象,handler里的MessageQueue对象就是looper对象里的MessageQueue对象,或者换一种说法:handler和looper共用一个消息队列。就这样handler和消息队列绑定上了。private Looper(boolean quitAllowed) { <strong> <span style="color:#FF0000;">mQueue = new MessageQueue(quitAllowed);</span></strong> mThread = Thread.currentThread(); }
下面我们先来看看Handler是怎么发送消息的,我们先从sendMessage(Message msg)这个方法看起:public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
当成功把该消息加入队列时返回true,否则为false。这个方法很简单,调用了sendMessageDelayed(Message msg,int delayed)方法,那么我们继续看看这个方法怎么实现的:public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
额,还是看不到具体怎么实现,继续看下去:
哎,还是看不到它是如何发消息的,但是我们可以看到这里调用了enqueueMessage方法的时候把成员变量mQueue(消息列队)传了进去,那么enqueueMessage这个方法内部又是怎么样的呢?我们继续:public boolean sendMessageAtTime(Message msg, long uptimeMillis) { <span style="color:#FF0000;"><strong>MessageQueue queue = mQueue;</strong></span> 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); }
看红色代码,把当前handler实例赋值给了要发送的消息的target属性,这个属性是什么呢?我们可以到Message源码去看个究竟!在Message源码中的成员变量中我们可以找到这么一句:private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { <span style="color:#FF0000;"><strong>msg.target = this;</strong></span> if (mAsynchronous) { msg.setAsynchronous(true); } <span style="color:#FF0000;"><strong>return queue.enqueueMessage(msg, uptimeMillis);</strong></span> }
也就是handler实例发消息的时候把自身赋值给了该消息的成员变量!这么做有么用?为么这么设计?答案稍后揭晓~ 嗯,回到enqueueMessage这个方法实体来,看最后的那句红色代码,意味着handler发送消息的本质是把消息交给自己的成员变量mQueue(消息队列)的enqueueMessage(Message msg, long when)方法去处理。这个时候handler就实现了发送消息并把消息提交到消息队列中的过程。/*package*/ Handler target;
那么,我们先看看消息队列是怎么把消息加入队列的,来到MessageQueue源码,找到enqueueMessage(Message msg, long when)boolean enqueueMessage(Message msg, long when) { if (msg.isInUse()) {//如果消息已经使用 throw new AndroidRuntimeException(msg + " This message is already in use."); } if (msg.target == null) {//如果没有handler throw new AndroidRuntimeException("Message must have a target."); } synchronized (this) { if (mQuitting) { RuntimeException e = new RuntimeException( msg.target + " sending message to a Handler on a dead thread"); Log.w("MessageQueue", e.getMessage(), e); return false; } <span style="color:#FF0000;"><strong> 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; }</strong></span> // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } return true; }
这个方法体:首先判断了加入的消息是否已用,已用则抛出异常。再判断消息的target属性是否为空,也就是判断发送该消息的handler对象是否为空,为空则抛出异常。(想一下,为什么?)然后我们直接看核心部分(红色代码部分),(这里先说一下,Message类成员变量中的next就是一个Message,这里可以理解为当前消息包含一个消息属性,就是包含下一个被消息队列取出的消息,可以理解为指针,当前消息有个指针指向下一个消息),mMessages是处在消息队列最前端即将被取出来的消息,if (p == null || when == 0 || when < p.when)这句代码的意思是:要么是第一次有消息提交上来,要么是传进来的消息的延迟触发时间为0,要么是传进来的消息的延迟触发时间在mMessages延迟触发的时间之前。那么就把新进来的消息插入到消息队列最前端。否则进入一个无限循环通过比较消息触发时间的前后来找到合适的插入位置,直到找到为止。至此就完成了把消息插入到消息队列中的过程。
那么,消息是发送出去了,并且已经加入消息队列了,怎么取出来处理? 嗯,我们先理一下,首先创建looper,然后创建handler,然后?然后当然就是取出消息了,这里调用looper.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();//获得与当前线程的looper实例 if (me == null) {//不存在则抛出异常 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue;//获得与looper对应的消息队列 // 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(); // 从消息队列中取出消息,没有消息则阻塞 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); } <span style="color:#FF0000;"><strong>msg.target.dispatchMessage(msg);</strong></span>//取出消息让消息本身的成员变量target的dispatchMessage方法去处理,其实就是handler去处理 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.recycle();//回收该消息 } }
代码中红色标识回答了上文中我们提出的问题。handler发消息的时候把自身赋值给消息的target属性,由于从消息队列中取出消息时把消息交给消息的属性target(就是handler)处理,所以得在把消息加入消息队列的时候先判断target属性是否为空,如果为空到时候取出来的时候就找不到对象去处理这个消息啦,所以抛出异常。那么dispatchMessage这个方法怎么实现呢?/** * Handle system messages here. */ public void dispatchMessage(Message msg) { if (msg.callback != null) {//这里是post头的方法发送runnable对象从消息队列取出后的处理方法 handleCallback(msg); } else {//否则是send开头方法发送的消息从消息队列取出的处理方法 if (mCallback != null) {//如果在创建handler的时候传入Callback接口不为空 if (mCallback.handleMessage(msg)) {//并且Callback接口方法消耗了该消息则返回,这里我们可以看到,如果我们要拦截消息,就可以让callback return; //接口的方法返回true,以便消耗了该消息,使得handler的handlerMessage方法无法接收到消息和处理。 } } <span style="color:#FF0000;"><strong> handleMessage(msg);</strong></span> } }
上面红色代码就是最终调用来处理消息的方法(假设前面消息没有被消耗),该方法就是在handler源码中是空方法,就是需要我们自己实现来处理消息的。/** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { }
至此,整个流程,已经真相大白了。妈妈再也不用担心我不了解handler了~!对了——post系列方法没说呀,消息队列不是只接收message对象么?是的,post系列方法最终调用的还是sendMessageAtTime方法,这里取个栗子~:
getPostMessage方法就是把一个runnable对象封装成一个消息,然后提交到消息队列中去。我们看看这个方法是怎么样的:public final boolean post(Runnable r) { return sendMessageDelayed(<span style="color:#FF0000;">getPostMessage(r)</span>, 0); }
然后在从消息队列中取出的时候,处理方法是handleCallback(Message msg):private static Message getPostMessage(Runnable r) { Message m = Message.obtain();//从消息池里拿出一个消息, m.callback = r;//把runnable对象复制给该消息的成员变量 return m; }
这就是我们传进去之前已经实现的runnable.run()方法,至此,至此,至此,handler就像个羞答答的裸体美女站在我们面前无处躲藏!!!private static void handleCallback(Message message) { message.callback.run(); }
对了,前面讲了怎么把消息加入消息队列中,那么取出是怎么取出的,我们都知道是messagequeue.next()方法取出,但是它是怎么实现的呢,我们来进入源码分析分析:
从消息队列中不断地取出消息,如果当前消息还没到触发时间,则设置下次轮询时间。否则取出。代码中已经注释很清楚了~Message next() { int pendingIdleHandlerCount = -1; // -1 only during first iteration int nextPollTimeoutMillis = 0; for (;;) {//无限循环取出 if (nextPollTimeoutMillis != 0) { Binder.flushPendingCommands(); } // We can assume mPtr != 0 because the loop is obviously still running. // The looper will not call this method after the loop quits. nativePollOnce(mPtr, nextPollTimeoutMillis); synchronized (this) { // Try to retrieve the next message. Return if found. final long now = SystemClock.uptimeMillis(); Message prevMsg = null; <strong> <span style="color:#FF0000;">Message msg = mMessages;</span></strong>//消息队列最前端要被取出的消息 if (msg != null && msg.target == null) {//如果消息没有handler处理 // 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;//能走到这步说明异步消息的next为非异步消息,也就是prevMsg.next是下一个是要被取出消息列队的消息 } else {//否则把取出消息的next赋值给下一个取出的消息 mMessages = msg.next; } msg.next = null; if (false) Log.v("MessageQueue", "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("MessageQueue", "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; } }
好了,handler、looper、messagequeue都分析完了。如果有什么问题,大家可以一起探讨~