之前說了Android消息分發(fā)和多線程切換的核心知識(shí)點(diǎn),這次來說一下消息傳遞的整個(gè)過程,好像上一篇內(nèi)容不看貌似也可以直接看這篇,不過建議還是看一下可以了解的更透徹一點(diǎn)吧~~
上一篇請(qǐng)看:http://www.itdecent.cn/p/e914cda1b5fe
下面開始本篇的主題吧,我將按照Handler和Message的一般使用流程,跟著代碼調(diào)用鏈一步步往下走,所以,看代碼吧!
首先在主線程定義一個(gè)handler:
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case TEST:
handleTest(msg);
break;
default:
handleDefault(msg);
break;
}
}
};
然后在工作線程中使用拿到handler的引用,直接使用:
new Thread(){
@Override
public void run() {
super.run();
Message message = Message.obtain();
message.what = TEST;
Bundle bundle =new Bundle();
bundle.putString("test key","test value");
message.setData(bundle);
handler.sendMessage(msg);
}
}.start();
以上即為一個(gè)簡(jiǎn)單使用場(chǎng)景,在工作線程中通過將Message發(fā)送到主線程的handler,讓handler在主線程中處理UI相關(guān)的操作。
我們從第一段代碼開始,先看一下Handler的創(chuàng)建過程。很簡(jiǎn)單,直接new一個(gè)Handler對(duì)象,然后實(shí)現(xiàn)它的handleMessage(Message msg)方法,但是這個(gè)handler可不是隨便哪里都能創(chuàng)建的,相信很多同學(xué)肯定也碰到過在別的線程中創(chuàng)建handler報(bào)錯(cuò)的情況,類似Can't create handler inside thread that has not called Looper.prepare()這樣的錯(cuò)誤提示,為啥呢?
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
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;
}
最終調(diào)用到的構(gòu)造器中的第一處判斷是用來檢測(cè)內(nèi)存泄露相關(guān)的,我們不管,看mLooper變量的賦值:
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
sThreadLocal.get()方法上一篇我們講過了,sThreadLocal是一個(gè)全局的靜態(tài)變量,保存著線程對(duì)應(yīng)的looper對(duì)象,get()方法用來獲取當(dāng)前線程對(duì)應(yīng)的looper對(duì)象,由于我們這個(gè)handler是在主線程中創(chuàng)建的,而主線程在ActivityThread的main()方法中已經(jīng)為我們創(chuàng)建了對(duì)應(yīng)的looper對(duì)象,因此我們這里去get的話是能取到值的,所以下面一行的判斷不會(huì)拋異常。但是一般的工作線程,我們?nèi)绻麤]用為它創(chuàng)建Looper對(duì)象,它是沒有對(duì)應(yīng)的Looper對(duì)象保存在sThreadLocal中的,因此Looper.myLooper()就會(huì)返回null,接下去就會(huì)報(bào)錯(cuò),也就是上面說的在工作線程中創(chuàng)建handler會(huì)報(bào)錯(cuò)的原因。取到mLooper之后,將mLooper中的保存Message的MessageQueue也取出保存在handler的屬性mQueue中,然后將構(gòu)造器的參數(shù)callback和async賦值,我們這里都為null。
這里大致介紹下Handler的幾個(gè)屬性:
-
boolean mAsynchronous:
這個(gè)是用來表明處理Message的時(shí)候是否需要保證順序,默認(rèn)為false,而且我們其實(shí)也沒辦法去將他設(shè)置為true,因?yàn)檫@些構(gòu)造器都是
@hide的,所以我們可以不管它。 -
Callback mCallback:
這個(gè)是Handler的內(nèi)部接口Callback類型的一個(gè)屬性,它就一個(gè)方法,也叫
handleMessage(Message msg),只能在構(gòu)造器中傳參,如果我們?cè)跇?gòu)造器中給了這個(gè)參數(shù),那么發(fā)送給這個(gè)handler的消息將優(yōu)先會(huì)由這個(gè)mCallback來執(zhí)行,不過目前為止我并不清楚哪些場(chǎng)景適用這種方式,知道的同學(xué)歡迎指教一下~ -
Looper mLooper:
handler是用來處理Message的,因此我們必須要有Message來源,而Message的來源MessageQueue是在Looper中的,因此handler需要一個(gè)Looper屬性。一般情況下mLooper即為主線程或者說是創(chuàng)建它的線程所對(duì)應(yīng)的Looper,但是我們也可以傳一個(gè)Looper對(duì)象給它,關(guān)于這個(gè)可以看看
HandlerThread的相關(guān)知識(shí)。 -
MessageQueue mQueue:
沒啥好說的,這個(gè)就是handler要處理的消息的來源了,它和Looper中的mQueue指向同一個(gè)對(duì)象。
在看一下Handler的消息分發(fā)方法:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
還記得上一篇中最后線程停留的那個(gè)死循環(huán)嗎,里面有一行代碼msg.target.dispatchMessage(msg);,這里每次取出的Message都會(huì)被它對(duì)應(yīng)的target也就是Handler對(duì)象分發(fā),也就是上面這段代碼。
可以看到首先會(huì)判斷Message對(duì)象自己的callback是否為空,它是一個(gè)Runnable對(duì)象,如果不為空直接調(diào)用callback的run()方法,否則判斷handler的屬性mCallback是否為空,屬性介紹的時(shí)候已經(jīng)講過這個(gè)了,如果不為空則則調(diào)用mCallback.handleMessage(msg)方法,這個(gè)方法返回true就直接return,否則調(diào)用handler的handlerMessage(msg)方法,也就是我們要繼承Handler要實(shí)現(xiàn)的方法,這個(gè)是不是有點(diǎn)類似于Android系統(tǒng)的屏幕事件傳遞機(jī)制呢?哈哈~
話說第一篇里有個(gè)坑還沒填,就是如何在工作線程創(chuàng)建使用Handler,不過相信看到這里的同學(xué)應(yīng)該已經(jīng)心里有底了吧,參考上一篇中ActivityThread中的main()方法,很容易創(chuàng)建自己的無線循環(huán)工作線程了,下面直接給出代碼:
new Thread(){
Handler handler;
@Override
public void run() {
super.run();
Looper.prepare();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//handler the message
}
};
Looper.loop();
}
};
以上,即在工作線程中創(chuàng)建了handler,然后將handler的引用丟給別的線程,別的線程就可以通過handler發(fā)消息到這個(gè)工作線程來處理。
Handler對(duì)于消息的分發(fā)和處理的邏輯總算說完了,接下去看看Message是如何被送到Handler的。
先看下Message的基本信息吧:
-
int what:
表明消息的類別,handler根據(jù)這個(gè)字段來判斷如何處理這個(gè)Message
-
Bundle data:
用于存放數(shù)據(jù),可以存放一些相對(duì)復(fù)雜的內(nèi)容,因此開銷稍微大一點(diǎn)
-
int arg1,arg2:
兩個(gè)基本類型的參數(shù),用于傳遞一些簡(jiǎn)單的Message信息,可以的話盡量用這兩個(gè)參數(shù)來傳遞信息,相對(duì)于Bundle data它性能消耗會(huì)小很多
-
int flags:
當(dāng)前Message狀態(tài)的一個(gè)標(biāo)志位,類似異步,使用中這些狀態(tài)
-
long when:
表示這個(gè)Message應(yīng)該在何時(shí)被執(zhí)行,MessageQueue中Message就是以這個(gè)字段為來排序的
-
Handler target:
Message將要被發(fā)送的對(duì)象,也就是由哪個(gè)target來接受處理這個(gè)Message,這個(gè)字段必須不為null
-
Runnable callback:
這個(gè)講handler的時(shí)候說到過了,如果有這個(gè)字段,那么這個(gè)Message將由此callback來處理,注意下,它是一個(gè)Runnable
-
Message next:
由于Message在消息池中是鏈表的形式維護(hù)的,所以這個(gè)字段表示下一個(gè)Message對(duì)象
-
static Message sPool:
這個(gè)是靜態(tài)變量,指向當(dāng)前消息池的第一個(gè)空閑Message
-
static int sPoolSize:
消息池的大小,也就是剩余空閑Message的數(shù)量
-
static final int MAX_POOL_SIZE = 50;
不用解釋了吧?
再貼一下例子中的第二段代碼:
new Thread(){
@Override
public void run() {
super.run();
Message message = Message.obtain();
message.what = TEST;
Bundle bundle =new Bundle();
bundle.putString("test key","test value");
message.setData(bundle);
handler.sendMessage(msg);
}
}.start();
Message的獲取方式特別多,除了自己new一個(gè)外,其他基本都大同小異,最終都從Message消息池取一個(gè)空閑的Message使用,因?yàn)锳ndroid系統(tǒng)中到處都用到了Message,因此會(huì)需要大量的Message對(duì)象,使用消息池的方式可以減少頻繁的創(chuàng)建銷毀對(duì)象,大大的提高性能。我這里直接用最基本的方式獲取,Message.obtain();,看源碼吧:
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
對(duì)著上面的字段介紹,很容易看出這個(gè)方法的作用就是將消息池的第一個(gè)空閑Message拿出來,然后消息池的數(shù)量減1,當(dāng)然如果消息池已經(jīng)沒用空閑Message了,那就new一個(gè)返回了。
例子中只用到了what和data字段,簡(jiǎn)單給它們賦了值,然后就調(diào)用handler.sendMessage(msg); 將消息發(fā)送給了我們?cè)谥骶€程創(chuàng)建的handler了。
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
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);
}
前面兩個(gè)方法的注釋我沒貼,因?yàn)楦谌齻€(gè)方法內(nèi)容差不多,而且最終也都是調(diào)用第三個(gè)方法,所以看了第三個(gè)方法的注釋和方法體應(yīng)該很容易明白前兩個(gè)方法的作用。
第一個(gè)方法是直接將消息發(fā)送handler處理,所以它使用0毫秒的延時(shí)作為參數(shù)調(diào)用第二個(gè)方法,第二個(gè)方法判斷如果延時(shí)小于0則默認(rèn)給0,因?yàn)樾∮?的延遲也就意味著比當(dāng)前時(shí)間早,當(dāng)然不可能回到過去處理這個(gè)消息了,然后它又將當(dāng)前時(shí)間加上延時(shí),調(diào)用了第三個(gè)方法,這樣第三個(gè)方法拿到的時(shí)間就是一個(gè)絕對(duì)值了,然后我們看到了mQueue,這個(gè)創(chuàng)建handler的時(shí)候我們就看到了,指向主線程對(duì)應(yīng)的Looper中的消息隊(duì)列,最后return了一個(gè)方法調(diào)用,看名字終于要加入消息隊(duì)列了。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
等等,原來我們剛才發(fā)送的Message還沒對(duì)象呢,那啥,我不是說那個(gè)對(duì)象,正經(jīng)點(diǎn)兒!所以加入消息隊(duì)列前先給它一個(gè)對(duì)象吧!然后如果我們的handler是異步的將msg的flag標(biāo)志位加上成異步,這下msg開開心心地領(lǐng)著對(duì)象去排隊(duì)了~
//MessageQueue
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
首先判斷Message的對(duì)象target是否為空(所以說Message不能沒有對(duì)象target),然后判斷Message是否正在使用中,在經(jīng)歷的前面的入隊(duì)步驟后,我們這個(gè)Message都滿足了條件,然后進(jìn)入一個(gè)同步塊,首先判斷是否正在退出中,因?yàn)橹骶€程是不可退出的,所以我們也不用考慮,不過里面方法也是一目了然,回收Message,返回false通知上層入隊(duì)失敗。我們繼續(xù)看滿足條件的情況下,將Message標(biāo)記為在使用中(msg.markInUse()),給when字段賦值,然后創(chuàng)建一個(gè)新對(duì)象指向消息隊(duì)列中的第一個(gè)消息mMessage,定義了一個(gè)布爾類型的字段needWake,表示是否需要喚醒當(dāng)前線程,因?yàn)闆]有消息需要處理的時(shí)候我們的Looper線程是阻塞的。當(dāng)消息隊(duì)列中的第一個(gè)消息為null或者我們本次需要入隊(duì)的消息對(duì)象msg的when為0或者小于原來的隊(duì)首消息的when值,則將msg插入到消息隊(duì)列的隊(duì)首,也就是mMessage之前,然后mMessage重新指向新的隊(duì)首,也就是msg;當(dāng)那些條件不滿足的時(shí)候,則需要將msg插入到消息隊(duì)列中而不是隊(duì)首,插入的方式也很簡(jiǎn)單除暴,遍歷原隊(duì)列的消息,依次比對(duì)when的值,直到隊(duì)尾或者找到下一個(gè)消息的when值比msg的when值大的時(shí)候跳出循環(huán),將msg插到其中,這個(gè)入隊(duì)的過程也就完成了,都是一些鏈表的基本操作。之前也有說到,因?yàn)槊看斡邢⑦M(jìn)入mQueue,我們都是以這種方式來插入的,所以有序的消息隊(duì)列就是簡(jiǎn)單以消息的when的大小來排序的。消息插入到消息隊(duì)列完成后,判斷是否需要喚醒主線程,需要?jiǎng)t調(diào)用native方法nativeWake()喚醒主線程來處理消息(Message msg = queue.next();//Looper.loop()方法中被喚醒后取出消息并分發(fā)處理)。最后返回true表明消息插入隊(duì)列成功。這樣Message入隊(duì)的過程就算完成了,是不是挺簡(jiǎn)單的~
以上,就是一個(gè)完整的消息傳遞和分發(fā)過程。實(shí)際使用中,我們用到更多的可能是handler.post(runnable);,handler.postDelayed(runnable,delayMillis);,view.postDelayed(runnable,delayMillis);之類的方法,這些方法看上去好像沒有Message什么事,但是點(diǎn)進(jìn)去一看就發(fā)現(xiàn),這個(gè)被post的runnable就是Message的callback,簡(jiǎn)單封裝一下就又走上了剛剛講完的消息傳遞路線,還沒反應(yīng)過來的回頭看看handler的dispatchMessage(Message msg)方法,因此這些方式我們都不用重寫handleMessage(Message msg)方法,使用起來非常方便。友情提示:非常方便的同時(shí)也非常容易導(dǎo)致內(nèi)存泄露、空指針和其他一些狀態(tài)紊亂的錯(cuò)誤(別問我怎么知道的,死過太多腦細(xì)胞??),慎用?。?!