以下是个人总结:
一般我们都是直接Handle handle=new Handle();
但是子线程中直接new Handle会报错,因为Handle的构造方法中的mLooper = Looper.myLooper();这个地方是mLooper是从Looper.myLooper()中获取的。如果我们没用调用Looper. prepare()进行初始化的话,Looper.myLooper()获取到的值就会是空的。而Looper. prepare()是通过sThreadLocal.set(new Looper())的形式新建Looper对象的,ThreadLocal通过获取当前线程将数据存放new Looper()在ThreadLocalMap中;
然后消息队列在Looper的构造方法中被创建。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
然后准备工作完成,当我们用handle发送消息时,不管你怎么send,最终都会走
sendMessageAtTime,或者sendMessageAtFrontOfQueue;这两个的区别就是消息执行的时间不一样而已。而他们都会调用enqueueMessage这个方法执行消息的入队操作。需要注意的是msg.target = this;这一句。在消息上传入了当前的handle,后面在消息分发的时候就直接分发到哪个handle上了。
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);
}
最后我们还要调用Looper.loop()事件才会进行会发,来看下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 traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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();
}
}
看重要的代码:
for (;;) {
Message msg = queue.next(); // might block
………………
msg.target.dispatchMessage(msg);
…………
}
一个死循环,queue.next();链表一直next下去,告诉你可能会Block。
然后就是刚才说的要注意的msg.target,这个我们在上面在将消息入队之前进行了赋值,然后现在就是调用它的dispatchMessage方法,也就是handle的dispatchMessage方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
如果Message没有设置callback则直接调用handleMessage,反之刚执行handleCallback;