publicstatic Message obtain(Handler h, int what, Object obj) {
Message m = obtain();
m.target = h;
m.what = what;
m.obj = obj;
return m;
}
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
publicstatic Message obtain() {
synchronized (mPoolSync) {
if (mPool !=null) {
Message m = mPool;
mPool = m.next;
m.next =null;
return m;
}
}
returnnew Message();
}
看到这里我们应该明白为什么Google建议我们使用obtainMessage而不是new一个Message.这也是符合了Android中的对象回收机制。
publicvoid sendToTarget() {
target.sendMessage(this);//targe就是一个Handler
}
sendMessage()会调用下面的sendMessageAtTime()把Message加入MessagQueue;
publicboolean sendMessageAtTime(Message msg, long uptimeMillis){
boolean sent =false;
MessageQueue queue = mQueue;
if (queue !=null) {
msg.target =this;
sent = queue.enqueueMessage(msg, uptimeMillis);
}else {
RuntimeException e =new RuntimeException(
this+" sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
}
return sent;
}
到此我们的Message对象被加入到了Handler所在线程(也就是主线程)中的MessageQueue这个存储和管理Message的容器当中。下一步就该由Looper接手一个一个的取出Message对象处理了。Looper最主要的方法就是loop()方法
publicstaticfinalvoid loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
while (true) {//死循环
Message msg = queue.next(); // might block
if (msg !=null) {
if (msg.target ==null) {//退出死循环的机制
// No target is a magic identifier for the quit message.
return;
}
if (me.mLogging!=null) me.mLogging.println(
">>>>> Dispatching to "+ msg.target +""
+ msg.callback +": "+ msg.what
);
msg.target.dispatchMessage(msg);//target of a msg is a Handler
if (me.mLogging!=null) me.mLogging.println(
" Finished to "+ msg.target +""
+ msg.callback);//msg.callback is a Runnable
msg.recycle();
}
}
}
Looper会一直阻塞读取MessagQueue中的Message对象(Message msg = queue.next()),当读取到一个Message时就会调用msg.target.dispatchMessage(msg)把这个Message分发给对应的Handler去处理,等Handler把任务处理完了再接着读取下一个Message对象并处理。