官方文档这样介绍 Handler
Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
意思是每个handler实例都关联一个线程以及这个线程的message queue,一旦handler创建,它就和线程绑定了。handler的作用是传递信息和runnable至message queue ,并且在信息和runnable从消息队列返回时处理他们。
根据上面的描述,我绘制了一个比较简单的handler工作原理图
假设我们现在有两个线程,线程B想要通过handler发消息给线程A,具体是怎么一个过程呢。
很简单,线程A拥有自己的
Handler :1、负责发送消息和runnable到消息队列 2、处理从消息队列返回的消息和runnable
消息队列:负责存放待处理的消息。
Looper :负责循环遍历消息队列,根据先进先出原则取出待处理消息发送给handler
当线程B想要发送消息到线程A处理时,它只需要获取线程A中的handler实例,调用handler的几个基础方法发送消息即可,这些消息会被线程A的handler实例传递到线程A的消息队列等待处理,当线程A的looper循环遍历到他们时,就会被传递到线程A的handler实例进行处理,整个过程就完成了。
那么我们可以看一看源码,是不是这样一个过程呢
从handler的构造函数入手
public Handler() {//无参构造函数调用了带两个参数的构造函数
this(null, false);
}
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());
}
}
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;
}
上面这个方法非常重要!它做了啥事情呢
1、检查了创建handler的类是不是内部类,如果是内部类是不是静态的,不然则做出提示
The following Handler class should be static or leaks might occur
这个提示是不是非常眼熟,嘻嘻。
为什么要做这个检查呢,我之前发表过一篇文章进行讨论,有兴趣可以参考 点击打开链接
2、 mLooper = Looper.myLooper(); 获取了一个looper对象,如果该对象为空,则抛出异常
Can't create handler inside thread that has not called Looper.prepare()
嘻嘻,也是很眼熟吧,当我们在子线程创建handler时,这个异常一言不合就抛出了。那么我们可以看看这个Looper.prepare()到底干了啥吧
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));
}
它做的事情很简单,检查当前线程有没有looper对象,有则抛出异常提示线程已经拥有自己的looper对象。没有就为当前线程创建一个looper对象
回到handler的构造函数,在获取了自己的looper对象以后,它又做了什么
3、mQueue = mLooper.mQueue; 获取message queue对象
到这里我们可以看到,Handler的构造函数做了两件重要的事情,一是创建looper对象,二是获取消息队列
接下来,我们看一看Handler是怎么传递消息的,依然从源码入手
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
再多的这里就不贴了,因为无论从handler哪一个发送消息的方法入手,最终调用的都是queue.enqueueMessage(msg, uptimeMillis)。我们主要看一看这个enqueueMessage(msg, uptimeMillis)方法是干了啥
boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
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;
}
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;
}
别看这个方法里又是判断又是循环的,实际上它的任务很简单,就是把刚刚发送过来的message插入到消息队列中合适的位置,为了便于理解,还是稍微讲几句它的核心代码
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;
}
先解释一下这里的mMessage,它是处于消息队列头部的消息,if判断语句说的是,如果这个消息队列头为空,或者是新消息的延迟为0,或者是新消息的延迟小于队列头消息的延迟时,直接把新消息置于队列头部。不然的话
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;
}
需要根据新消息的延迟将它插入至队列中合适的位置,这里的for循环做的就是遍历消息队列,依次对比新消息和每一条消息的延迟,直至找到比新消息延迟大的第一条消息。
到这里,handler的构造函数和消息传递,我们都看到了,结合上图会不会更清晰一点呢。接下来,我们就看looper是如何循环遍历消息队列的吧
/**
* 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
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);
}
// 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();
}
}
我们依旧只看最关键的代码
public static void loop() {
final Looper me = myLooper();
……
final MessageQueue queue = me.mQueue;
……
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
……
msg.target.dispatchMessage(msg);
……
msg.recycle();
}
}
这个方法先拿到消息队列,然后开启一个for循环,从消息队列中依次取出每一条消息,然后调用msg.target.dispatchMessage(msg)进行处理
这个msg.target是啥呢,这里必须说一下,其实这个target就是handler对象
如果我们发送消息时采用的是handler的一系列方法(
sendMessage(Message msg)
sendEmptyMessage(int what)
sendEmptyMessageDelayed(int what, long delayMillis)
……
)
他们最终都会调用到一个方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在这里handler将自己赋值给message对象的target
如果我们发送消息时采用的是Message的一系列方法
obtain(Handler h) +sendToTarget()
obtain(Handler h, Runnable callback) +sendToTarget()
每一个obtain方法中,都会将handler赋值给message对象的target,这里就不贴出代码了。
所以msg.target.dispatchMessage(msg),其实就是message对象调用它所绑定的handler的方法,处理本身了。我们最后看看这个dispatchMessage(msg)方法
/**
* 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);
}
}
这个方法做的事情很简单,判断回调有没有被实现,如果回调被实现则调用相应的方法,不然就调用handleMessage方法。
到这里handler的工作原理和源码讲解就全部结束了,小女子火候尚浅,若有不对的地方,还请各位侠士指教了。O(∩_∩)O~~