Handler機(jī)制實(shí)現(xiàn)線程間通信
如何實(shí)現(xiàn)
通過send或post方法將message提交到當(dāng)前handle所在線程的MessageQueue中延赌,當(dāng)前線程關(guān)聯(lián)的Looper不斷循環(huán)在messageQueue中取出message
msg.target.dispatchMessage(msg);
分發(fā)給對(duì)應(yīng)的handler消耗Looper是什么
我們通過Looper().prepare()給當(dāng)前線程設(shè)置一個(gè)Looper晶疼,其關(guān)聯(lián)函數(shù)如下
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//用以判斷當(dāng)前線程是否已創(chuàng)建Looper
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//新建Looper對(duì)象與當(dāng)前線程綁定
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
//一個(gè)Looper對(duì)象管理一個(gè)MessageQueue對(duì)象
mQueue = new MessageQueue(quitAllowed);
//獲取當(dāng)前Thread對(duì)象
mThread = Thread.currentThread();
}
執(zhí)行完Looper().prepare()后就為該線程創(chuàng)建了一個(gè)與之綁定的Looper對(duì)象嗤形,并且有一個(gè)受該Looper管理的MessageQueue吏祸,作為message的容器烘嘱。
new Thread(
new Runnable() {
@Override
public void run() {
Looper.prepare();
handler.sendEmptyMessage(0x123);
Looper.loop();
}
})
可以看到prerare()后還有一個(gè)loop()函數(shù)
public static void loop() {
//獲得Looper對(duì)象
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//得到該Looper對(duì)象管理的MessageQueue
final MessageQueue queue = me.mQueue;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
//執(zhí)行循環(huán)操作赚导,通過next()得到queue中的message分發(fā)到handler中被因,可能會(huì)堵塞
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//這里的target就是handler對(duì)象
msg.target.dispatchMessage(msg);
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);
}
//設(shè)置message處理完畢
msg.recycleUnchecked();
}
}
loop()函數(shù)會(huì)開啟循環(huán)卿拴,將MessageQueue中的message分配出去進(jìn)行處理
- Handler發(fā)出message與處理
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());
}
}
//獲得當(dāng)前線程的Looper對(duì)象
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//取出MessageQueue對(duì)象
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
在線程中創(chuàng)建handler時(shí),我們就已經(jīng)給handler對(duì)象傳遞了當(dāng)前線程對(duì)應(yīng)的唯一的MessageQueue
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
//獲取該handler所在線程的MessageQueue
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賦值
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
到這里梨与,我們就給將 message加入到handler所在線程對(duì)應(yīng)的MessageQueue中堕花,并且指定了處理message的handler。
///Loop()方法中調(diào)用此方法粥鞋,執(zhí)行對(duì)message的處理
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
一個(gè)線程只能有一個(gè)Looper缘挽,且只能有一個(gè)MessageQueue,但是可以綁定多個(gè)handler處理不同事件
HandlerThread
繼承自Thread呻粹,自身帶有一個(gè)Looper對(duì)象壕曼,可用來新建handler。一般用來執(zhí)行耗時(shí)操作等浊,與自定義Thread再執(zhí)行Looper.prepare()效果相同腮郊。