常见的使用Handler线程间通讯:
主线程:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
...
}
};
子线程:
Message message = new Message();
message.arg1 = 1;
Bundle bundle = new Bundle();
bundle.putString("test", "test");
message.setData(bundle);
handler.sendMessage(message);
这类操作一般用于在子线程更新UI。在主线程创建一个handler,重写handlermessage方法,然后在子线程里发送消息,主线程里就会接受到消息。这就是简单的线程间通讯。如果在子线程创建handler对象则会报错。根据Log提示,子线程创建handler需要调用Looper.prepare() (在main函数中已经调用了Looper.prepareMainLooper(),该方法内会调起Looper.prepare()),Looper.loop()方法 。但是即使子线程调用Looper.prepare()创建Looper对象,这个Looper也是子线程的,不可以用于更新UI操作。那到底Handler、Looper这几个类之间是如何工作的呢?我们从源头看起,以下是Looper类的prepare()方法:
public final class Looper {
...
final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); //threadLocal是线程内部的数据存储类,该类存储了线程的所有数据信息。
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的构造器里也创建了一个MessageQueue,),将Looper与线程关联起来
}
public static @Nullable Looper myLooper() { //下面会看到的,设置Handler类里的Looper时会调用该方法
return sThreadLocal.get(); //获得Looper对象
}
...
}
当handler传输message时,不论是调用sendMessage(Message msg)还是sendMessageDelayed(),最后都会指向sendMessageAtTime()方法:
public class 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);
}
...
}
mQueue即消息队列,用于将收到的消息以队列形式排列,提供出队和入队方法,该变量是Looper的成员变量,在Handler创建时赋值给handler
public class Handler {
...
final Looper mLooper;
final MessageQueue mQueue;
mLooper = Looper.myLooper(); //创建Handler前调用Looper.prepare()时定义并设置了Looper,这里调用Looper.myLooper()来获得该Looper
mQueue = mLooper.mQueue;
...
}
上面调用的enqueueMessage(queue, msg, uptimeMillis)方法作用是消息入队
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this; //把handler本身赋值给要入队的消息,用来待会儿出队使用
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
可以看到最后是由消息队列queue调用自身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;
}
mMessages是MessageQueue类的一个成员变量,用以记录排在最前面的消息,msg是我们传入的message,msg.next是Message类的成员变量,可以理解成下一条消息。入列方法重点看这几句:
Message p = mMessages;
msg.next = p; //把mMessages赋值给新入队的这条消息的next
mMessages = msg; //把新入队的消息赋值给mMessages
就像排队一样,msg是来插队的,排第一的mMessages自愿排到msg的后面,并让msg站到自己原来的位置上,这样就完成的msg的入队操作,整个消息入队操作是按照时间来排序的。至于出队操作,就在一开始所提到的ActivityTread中的main方法里调用的Looper.loop()方法里:
public static void loop() {
...
for (;;) {
...
Message msg = queue.next(); //获取下一条消息
...
msg.target.dispatchMessage(msg); //传递消息
...
msg.recycleUnchecked(); //清空状态,循环往复
}
}
...
}
提炼出来就是在loop方法里一直死循环,从MessageQueue消息队列里使用next()方法获得下一条消息,next方法简单看就是:
Message msg = mMessages;
mMessages = msg.next;
msg.next = null;
return msg;
这就是简单的解释消息出列,把排第一的消息作为方法的返回值,然后让排第二的排到第一去。获得消息后使用msg.target(上面入队时赋值的handler)来传递消息:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg); //如果有callback参数则调用处理回调的方法
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg); //将消息作为参数传递出去
}
}
至此,handler传递消息的整个流程走完。另外还有一个我们经常用到handler的方法post:
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) { //将runnable变成message自身的callback变量
Message m = Message.obtain();
m.callback = r;
return m;
}
可以看到,post的runnable参数经过getPostMessage()方法最后被赋值给要传递下去的消息的callback这个变量,等到消息出列时,如果消息带有callback参数则调用处理回调的方法handleCallback(msg)
private static void handleCallback(Message message) {
message.callback.run();
}
可以看到,不论是从sendMessage里发出的消息,还是在post传递的runnable里执行的代码,最后都是殊途同归,都是在UI线程运行的。最后总结一下吧,线程间通讯原理大概就是:
- Looper.prepare()创建Looper和MessageQueue,并与所在线程关联
- Looper.loop()通过一个for死循环不断对MessageQueue进行轮询
- 创建handler时,会把Looper和MessageQueue赋值给handler,将三者关联起来。当handler调用sendMessage传递消息,消息会被发送到Looper的消息队列MessageQueue里
- 一旦loop()方法接收到消息,则将消息通过该消息携带的handler(msg.target)的handleMessage方法处理