1.何謂Handler機(jī)制唱矛?
一般來(lái)說(shuō),當(dāng)你的應(yīng)用被創(chuàng)建的時(shí)候蛀醉,會(huì)創(chuàng)建一條應(yīng)用的主線(xiàn)程。因?yàn)樾实目紤]衅码,所有的View和Widget都不是線(xiàn)程安全的拯刁,所以相關(guān)操作強(qiáng)制放在同一個(gè)線(xiàn)程,這樣就可以避免多線(xiàn)程帶來(lái)的問(wèn)題逝段。這個(gè)線(xiàn)程就是主線(xiàn)程垛玻,也即UI線(xiàn)程。
當(dāng)然奶躯,你可以創(chuàng)建自己的線(xiàn)程去做操作帚桩,但如何應(yīng)用的主線(xiàn)程通信呢。那就要使用到Handler機(jī)制了嘹黔。如果你將一個(gè)Handler和你的UI線(xiàn)程連接账嚎,處理消息的代碼就將會(huì)在UI線(xiàn)程中執(zhí)行。新線(xiàn)程和UI線(xiàn)程的通信是通過(guò)從你的新線(xiàn)程調(diào)用和主線(xiàn)程相關(guān)的Handler對(duì)象的相關(guān)方法實(shí)現(xiàn)的。
那接下來(lái)就要介紹一下這個(gè)消息通訊機(jī)制Handler郭蕉,涉及到三個(gè)主要的類(lèi):Looper疼邀,Handler和Message類(lèi)。
2.Looper
重點(diǎn)方法為:prepare()和loop()
Looper#prepare():
private static final ThreadLocal sThreadLocal = new ThreadLocal();
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
} ```
解釋?zhuān)菏紫人鼊?chuàng)建了一個(gè)ThreadLocal對(duì)象召锈,它是一個(gè)線(xiàn)程內(nèi)部的數(shù)據(jù)存儲(chǔ)類(lèi)旁振,通過(guò)它可以在指定的線(xiàn)程中存儲(chǔ)數(shù)據(jù)。然后在prepare方法中將looper存儲(chǔ)在線(xiàn)程里面烟勋。
Looper#Looper():
```java
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
} ```
而在構(gòu)造方法中规求,Looper創(chuàng)建了一個(gè)MessageQueue,雖然是叫queue但其實(shí)內(nèi)部實(shí)現(xiàn)是一個(gè)單鏈表卵惦。
Looper#loop():
```java
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
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.recycle();
}
public static Looper myLooper() {
return sThreadLocal.get();
}
}
解釋?zhuān)悍椒ㄖ苯臃祷亓饲懊鎠ThreadLocal存儲(chǔ)的Looper實(shí)例,如果me為null則拋出異常瓦戚,也就是說(shuō)looper方法必須在prepare方法之后運(yùn)行沮尿。拿到該looper實(shí)例中的mQueue即消息隊(duì)列后進(jìn)入了無(wú)限循環(huán),不斷從隊(duì)列中取出一條消息较解,如果沒(méi)有消息則阻塞畜疾。如果取得消息使用調(diào)用msg.target.dispatchMessage(msg);把消息交給msg的target的dispatchMessage方法去處理。而msg的target是什么呢印衔?其實(shí)就是前面講到的handler對(duì)象啡捶,最后會(huì)釋放消息占據(jù)的資源。
Looper類(lèi)總結(jié):
1.與當(dāng)前線(xiàn)程綁定奸焙,保證一個(gè)線(xiàn)程只會(huì)有一個(gè)Looper實(shí)例瞎暑,同時(shí)一個(gè)Looper實(shí)例也只有一個(gè)MessageQueue。
2.loop()方法与帆,不斷從MessageQueue中去取消息了赌,交給message的target的dispatchMessage去處理。
接下來(lái)就要講發(fā)送消息的對(duì)象了玄糟,這個(gè)對(duì)象就是Handler勿她。
3.Handler
主要作用是將一個(gè)任務(wù)切換到某個(gè)指定的線(xiàn)程中去執(zhí)行,同時(shí)為了解決在子線(xiàn)程中無(wú)法訪(fǎng)問(wèn)UI的矛盾阵翎。
所以我們首先看Handler的構(gòu)造方法逢并,看其如何與MessageQueue聯(lián)系上的。
Handler#Handler():
public Handler() {
this(null, false);
}
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;
}
解釋?zhuān)涸跇?gòu)造的時(shí)候會(huì)檢查當(dāng)前的Handler是否為靜態(tài)類(lèi)郭卫,不是靜態(tài)聲明的話(huà)會(huì)打印Log砍聊,提示會(huì)有內(nèi)存泄漏現(xiàn)象的產(chǎn)生,然后通過(guò)Looper.myLooper()方法獲取到當(dāng)前線(xiàn)程的Looper實(shí)例(mLooper)并進(jìn)一步獲取到當(dāng)前線(xiàn)程的消息隊(duì)列(mQueue)箱沦,這樣就保證了handler的實(shí)例與我們Looper實(shí)例中MessageQueue關(guān)聯(lián)上了辩恼。
使用的時(shí)候我們會(huì)經(jīng)常使用到sendMessage方法,我們來(lái)看看源碼實(shí)現(xiàn):
public final boolean sendMessage(Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}```
一路跳到最后的enqueueMessage方法,enqueueMessage中首先為msg.target賦值為this灶伊,因?yàn)長(zhǎng)ooper中的loop方法會(huì)取出每個(gè)msg然后交給msg,target.dispatchMessage(msg)去處理消息疆前,也就是把當(dāng)前的handler作為msg的target屬性。最終會(huì)調(diào)用queue的enqueueMessage的方法聘萨,保存到消息隊(duì)列中去竹椒。
現(xiàn)在已經(jīng)很清楚了Looper會(huì)調(diào)用prepare()和loop()方法,在當(dāng)前執(zhí)行的線(xiàn)程中保存一個(gè)Looper實(shí)例米辐,這個(gè)實(shí)例會(huì)保存一個(gè)MessageQueue對(duì)象胸完,然后當(dāng)前線(xiàn)程進(jìn)入一個(gè)無(wú)限循環(huán)中去,不斷從MessageQueue中讀取Handler發(fā)來(lái)的消息翘贮。然后再回調(diào)創(chuàng)建這個(gè)消息的handler中的dispatchMessage方法赊窥。
Handler#dispatchMessage():
```java
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// 如果message設(shè)置了callback,即runnable消息狸页,處理callback锨能!
handleCallback(msg); // 并直接調(diào)用callback的run方法!
} else {
// 如果handler本身設(shè)置了callback芍耘,則執(zhí)行callback
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
// 如果message沒(méi)有callback址遇,則調(diào)用handler的鉤子方法handleMessage
handleMessage(msg);
}
}```
幾個(gè)變量和方法的解釋?zhuān)?
1.callback:message攜帶的Runnable對(duì)象,實(shí)際上就是Handler的post方法所傳遞的Runnable參數(shù)斋竞。
我們來(lái)看一下Handler的post方法源碼實(shí)現(xiàn):
```java
mHandler.post(new Runnable() {
@Override
public void run() {
// code
}
});```
其實(shí)這個(gè)Runnable并沒(méi)有創(chuàng)建什么線(xiàn)程倔约,而是發(fā)送了一條消息:
```java
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}```
在getPostMessage中,得到了一個(gè)Message對(duì)象坝初,然后將我們創(chuàng)建的Runable對(duì)象作為callback屬性浸剩,賦值給了此message。
注意:產(chǎn)生一個(gè)Message對(duì)象脖卖,可以new乒省,也可以使用Message.obtain()方法;兩者都可以畦木,但是更建議使用obtain方法袖扛,因?yàn)镸essage內(nèi)部維護(hù)了一個(gè)Message池用于Message的復(fù)用,避免使用new重新分配內(nèi)存十籍。
2.mCallback:可通過(guò)Handler handler = new Handler(callback); 可以用來(lái)創(chuàng)建一個(gè)Handler實(shí)例但不需要派生Handler子類(lèi)蛆封。它可用來(lái)攔截消息!當(dāng)mCallback的handleMessage返回true的時(shí)候可以攔截消息勾栗,具體的邏輯看上面的代碼很容易理解惨篱!
3.handleMessage(msg):它是一個(gè)空方法,為什么呢围俘,因?yàn)橄⒌淖罱K回調(diào)是由我們控制的砸讳,我們?cè)趧?chuàng)建handler的時(shí)候都是復(fù)寫(xiě)handleMessage方法琢融,然后根據(jù)msg.what進(jìn)行消息處理。
到此簿寂,這個(gè)流程已經(jīng)解釋完畢漾抬,總結(jié)一下:
1.首先Looper.prepare()在本線(xiàn)程中保存一個(gè)Looper實(shí)例,然后該實(shí)例中保存一個(gè)MessageQueue對(duì)象常遂;因?yàn)長(zhǎng)ooper.prepare()在一個(gè)線(xiàn)程中只能調(diào)用一次纳令,所以MessageQueue在一個(gè)線(xiàn)程中只會(huì)存在一個(gè)。
2.Looper.loop()會(huì)讓當(dāng)前線(xiàn)程進(jìn)入一個(gè)無(wú)限循環(huán)克胳,不端從MessageQueue的實(shí)例中讀取消息平绩,然后回調(diào)msg.target.dispatchMessage(msg)方法。
3.Handler的構(gòu)造方法漠另,會(huì)首先得到當(dāng)前線(xiàn)程中保存的Looper實(shí)例捏雌,進(jìn)而與MessageQueue相關(guān)聯(lián)。
4.Handler的sendMessage方法酗钞,會(huì)給msg的target賦值為handler自身腹忽,然后加入MessageQueue中。
5.在構(gòu)造Handler實(shí)例時(shí)砚作,我們會(huì)重寫(xiě)handleMessage方法,也就是msg.target.dispatchMessage(msg)嘹锁。
6.在A(yíng)ctivity中葫录,我們并沒(méi)有顯示的調(diào)用Looper.prepare()和Looper.loop()方法,是因?yàn)樵贏(yíng)ctivity的啟動(dòng)代碼中领猾,已經(jīng)在當(dāng)前UI線(xiàn)程調(diào)用了Looper.prepare()和Looper.loop()方法米同。
下面是個(gè)人認(rèn)為在 Activity 中一個(gè)合格的 Handler 該有的樣子:
```java
private static class MyHandler extends Handler {
private WeakReference<CustomActivity> activityWeakReference;
public MyHandler(CustomActivity activity) {
activityWeakReference = new WeakReference<CustomActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
CustomActivity activtiy = activityWeakReference.get();
if (activity != null) {
// code
}
}
} ```