Handler是线程间切换的一种方式,Handler的运行机制主要就是Handler,Looper,Message,MessageQueue和ThreadLocal之间是如何实现消息的传递的,下面用一张图简单说明一下Handler的消息机制。
这其中最关键的部分在于:
1.Handler调用sendMessage之后是如何把Message插入到MessageQueue中的?
2.Looper是如何从MessageQueue取出这个消息的?
1.Handler调用sendMessage之后是如何把Message插入到MessageQueue中的?
我们先思考一下,如果想要把一个message加入到MessageQueue中那么我们肯定要调用MessageQueue的enqueueMessage方法,那么我们必须要拿到MessageQueue的对象才能调用MessageQueue的方法,所以我们只要关注Handler中如何拿到MessageQueue的对象就能找到第一个问题的答案了。
看一下sendMessage的源码
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);
}
sendMessage调用之后最终会调用sendMessageAtTime方法,在此方法中我们找到了MessageQueue的对象,接着找这个MessageQueue对象是如何创建的?
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;
}
在Handler的构造方法中,找到了mQueue 的踪迹,mQueue = mLooper.mQueue;是通过Looper的对象拿到的,难道Looper中保存了MessageQueue的对象?
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
果不其然,Looper的构造方法中实例了MessageQueue对象,也就是说,handler中的MessageQueue对象是通过Looper的对象拿到的,那么还有另一个问题handler中又是怎么拿到Looper的对象呢?
handler的构造中有这么一段代码
mLooper = Looper.myLooper();
接着追
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
看到了ThreadLocal,ThreadLocal是线程内部的数据存储类,可以在指定线程中存储数据,存储的数据只能在这个指定的线程中获取。通过ThreadLocal的get方法获取数据,set方法存储数据。
那我们接着看ThreadLocal到底存了什么数据,什么时候存的数据?
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<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");
}
sThreadLocal.set(new Looper(quitAllowed));
}
原来存的是Looper对象,在调用Looper的prepare方法的时候把Looper对象存到ThreadLocal中的啊(所以子线程中使用handler要先调用Looper.prepare方法)。
所以第一个问题:handler中的MessageQueue对象是通过Looper拿到的,Looper对象是通过Looper的静态方法myLooper从ThreadLocal中get出来的,ThreadLocal中的Looper对象是通过Looper的prepare方法存储的。
2.Looper是如何从MessageQueue取出这个消息的?
先看Looper的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();
}
}
loop方法是个死循环,不断从MessageQueue中读取消息,只有从MessageQueue中读取到的消息为null的时候才会结束循环,读取到的消息会调用 msg.target.dispatchMessage(msg);,msg.target是个什么东西呢?
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在handler调用sendMessage的时候最终会调用enqueueMessage方法,此时 msg.target = this;给 msg.target = this;赋值,也就是说这个msg.target就是发送这个消息的Handler对象,那dispatchMessage(msg);也就是把这个msg分发给Handler处理了。
分析完了,在下拙见,有错误欢迎指正。