之前說了Android消息分發(fā)和多線程切換的核心知識點娱仔,這次來說一下消息傳遞的整個過程配椭,好像上一篇內(nèi)容不看貌似也可以直接看這篇虫溜,不過建議還是看一下可以了解的更透徹一點吧~~
上一篇請看:http://www.reibang.com/p/e914cda1b5fe
下面開始本篇的主題吧雹姊,我將按照Handler和Message的一般使用流程股缸,跟著代碼調(diào)用鏈一步步往下走,所以吱雏,看代碼吧敦姻!
首先在主線程定義一個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();
以上即為一個簡單使用場景歧杏,在工作線程中通過將Message發(fā)送到主線程的handler镰惦,讓handler在主線程中處理UI相關(guān)的操作。
我們從第一段代碼開始犬绒,先看一下Handler的創(chuàng)建過程旺入。很簡單,直接new一個Handler對象凯力,然后實現(xiàn)它的handleMessage(Message msg)方法茵瘾,但是這個handler可不是隨便哪里都能創(chuàng)建的,相信很多同學(xué)肯定也碰到過在別的線程中創(chuàng)建handler報錯的情況咐鹤,類似Can't create handler inside thread that has not called Looper.prepare()
這樣的錯誤提示拗秘,為啥呢?
/**
* 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)造器中的第一處判斷是用來檢測內(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是一個全局的靜態(tài)變量捧请,保存著線程對應(yīng)的looper對象凡涩,get()方法用來獲取當(dāng)前線程對應(yīng)的looper對象,由于我們這個handler是在主線程中創(chuàng)建的疹蛉,而主線程在ActivityThread的main()方法中已經(jīng)為我們創(chuàng)建了對應(yīng)的looper對象突照,因此我們這里去get的話是能取到值的,所以下面一行的判斷不會拋異常氧吐。但是一般的工作線程讹蘑,我們?nèi)绻麤]用為它創(chuàng)建Looper對象,它是沒有對應(yīng)的Looper對象保存在sThreadLocal中的筑舅,因此Looper.myLooper()就會返回null座慰,接下去就會報錯,也就是上面說的在工作線程中創(chuàng)建handler會報錯的原因翠拣。取到mLooper之后版仔,將mLooper中的保存Message的MessageQueue也取出保存在handler的屬性mQueue中,然后將構(gòu)造器的參數(shù)callback和async賦值,我們這里都為null蛮粮。
這里大致介紹下Handler的幾個屬性:
-
boolean mAsynchronous:
這個是用來表明處理Message的時候是否需要保證順序益缎,默認(rèn)為false,而且我們其實也沒辦法去將他設(shè)置為true然想,因為這些構(gòu)造器都是
@hide
的莺奔,所以我們可以不管它。 -
Callback mCallback:
這個是Handler的內(nèi)部接口Callback類型的一個屬性变泄,它就一個方法令哟,也叫
handleMessage(Message msg),只能在構(gòu)造器中傳參,如果我們在構(gòu)造器中給了這個參數(shù)妨蛹,那么發(fā)送給這個handler的消息將優(yōu)先會由這個mCallback來執(zhí)行屏富,不過目前為止我并不清楚哪些場景適用這種方式,知道的同學(xué)歡迎指教一下~ -
Looper mLooper:
handler是用來處理Message的蛙卤,因此我們必須要有Message來源狠半,而Message的來源MessageQueue是在Looper中的,因此handler需要一個Looper屬性颤难。一般情況下mLooper即為主線程或者說是創(chuàng)建它的線程所對應(yīng)的Looper,但是我們也可以傳一個Looper對象給它神年,關(guān)于這個可以看看
HandlerThread
的相關(guān)知識。 -
MessageQueue mQueue:
沒啥好說的乐严,這個就是handler要處理的消息的來源了,它和Looper中的mQueue指向同一個對象瘤袖。
在看一下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();
}
還記得上一篇中最后線程停留的那個死循環(huán)嗎,里面有一行代碼msg.target.dispatchMessage(msg);
,這里每次取出的Message都會被它對應(yīng)的target也就是Handler對象分發(fā)昂验,也就是上面這段代碼捂敌。
可以看到首先會判斷Message對象自己的callback是否為空,它是一個Runnable對象既琴,如果不為空直接調(diào)用callback的run()方法占婉,否則判斷handler的屬性mCallback是否為空,屬性介紹的時候已經(jīng)講過這個了甫恩,如果不為空則則調(diào)用mCallback.handleMessage(msg)方法逆济,這個方法返回true就直接return,否則調(diào)用handler的handlerMessage(msg)方法磺箕,也就是我們要繼承Handler要實現(xiàn)的方法奖慌,這個是不是有點類似于Android系統(tǒng)的屏幕事件傳遞機(jī)制呢?哈哈~
話說第一篇里有個坑還沒填松靡,就是如何在工作線程創(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ā)消息到這個工作線程來處理啦逆。
Handler對于消息的分發(fā)和處理的邏輯總算說完了伞矩,接下去看看Message是如何被送到Handler的。
先看下Message的基本信息吧:
-
int what:
表明消息的類別夏志,handler根據(jù)這個字段來判斷如何處理這個Message
-
Bundle data:
用于存放數(shù)據(jù)乃坤,可以存放一些相對復(fù)雜的內(nèi)容,因此開銷稍微大一點
-
int arg1,arg2:
兩個基本類型的參數(shù)盲镶,用于傳遞一些簡單的Message信息侥袜,可以的話盡量用這兩個參數(shù)來傳遞信息蝌诡,相對于Bundle data它性能消耗會小很多
-
int flags:
當(dāng)前Message狀態(tài)的一個標(biāo)志位溉贿,類似異步,使用中這些狀態(tài)
-
long when:
表示這個Message應(yīng)該在何時被執(zhí)行浦旱,MessageQueue中Message就是以這個字段為來排序的
-
Handler target:
Message將要被發(fā)送的對象宇色,也就是由哪個target來接受處理這個Message,這個字段必須不為null
-
Runnable callback:
這個講handler的時候說到過了颁湖,如果有這個字段宣蠕,那么這個Message將由此callback來處理,注意下甥捺,它是一個Runnable
-
Message next:
由于Message在消息池中是鏈表的形式維護(hù)的抢蚀,所以這個字段表示下一個Message對象
-
static Message sPool:
這個是靜態(tài)變量,指向當(dāng)前消息池的第一個空閑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一個外吴侦,其他基本都大同小異屋休,最終都從Message消息池取一個空閑的Message使用,因為Android系統(tǒng)中到處都用到了Message备韧,因此會需要大量的Message對象劫樟,使用消息池的方式可以減少頻繁的創(chuàng)建銷毀對象,大大的提高性能织堂。我這里直接用最基本的方式獲取叠艳,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();
}
對著上面的字段介紹,很容易看出這個方法的作用就是將消息池的第一個空閑Message拿出來易阳,然后消息池的數(shù)量減1附较,當(dāng)然如果消息池已經(jīng)沒用空閑Message了,那就new一個返回了闽烙。
例子中只用到了what和data字段翅睛,簡單給它們賦了值声搁,然后就調(diào)用handler.sendMessage(msg); 將消息發(fā)送給了我們在主線程創(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);
}
前面兩個方法的注釋我沒貼捕发,因為跟第三個方法內(nèi)容差不多疏旨,而且最終也都是調(diào)用第三個方法,所以看了第三個方法的注釋和方法體應(yīng)該很容易明白前兩個方法的作用扎酷。
第一個方法是直接將消息發(fā)送handler處理檐涝,所以它使用0毫秒的延時作為參數(shù)調(diào)用第二個方法,第二個方法判斷如果延時小于0則默認(rèn)給0法挨,因為小于0的延遲也就意味著比當(dāng)前時間早谁榜,當(dāng)然不可能回到過去處理這個消息了,然后它又將當(dāng)前時間加上延時凡纳,調(diào)用了第三個方法窃植,這樣第三個方法拿到的時間就是一個絕對值了,然后我們看到了mQueue荐糜,這個創(chuàng)建handler的時候我們就看到了巷怜,指向主線程對應(yīng)的Looper中的消息隊列,最后return了一個方法調(diào)用暴氏,看名字終于要加入消息隊列了延塑。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
等等,原來我們剛才發(fā)送的Message還沒對象呢答渔,那啥关带,我不是說那個對象,正經(jīng)點兒沼撕!所以加入消息隊列前先給它一個對象吧宋雏!然后如果我們的handler是異步的將msg的flag標(biāo)志位加上成異步,這下msg開開心心地領(lǐng)著對象去排隊了~
//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的對象target是否為空(所以說Message不能沒有對象target),然后判斷Message是否正在使用中,在經(jīng)歷的前面的入隊步驟后,我們這個Message都滿足了條件端朵,然后進(jìn)入一個同步塊好芭,首先判斷是否正在退出中,因為主線程是不可退出的冲呢,所以我們也不用考慮舍败,不過里面方法也是一目了然,回收Message,返回false通知上層入隊失敗敬拓。我們繼續(xù)看滿足條件的情況下邻薯,將Message標(biāo)記為在使用中(msg.markInUse()
),給when字段賦值,然后創(chuàng)建一個新對象指向消息隊列中的第一個消息mMessage乘凸,定義了一個布爾類型的字段needWake,表示是否需要喚醒當(dāng)前線程厕诡,因為沒有消息需要處理的時候我們的Looper線程是阻塞的。當(dāng)消息隊列中的第一個消息為null或者我們本次需要入隊的消息對象msg的when為0或者小于原來的隊首消息的when值营勤,則將msg插入到消息隊列的隊首灵嫌,也就是mMessage之前壹罚,然后mMessage重新指向新的隊首,也就是msg寿羞;當(dāng)那些條件不滿足的時候猖凛,則需要將msg插入到消息隊列中而不是隊首,插入的方式也很簡單除暴绪穆,遍歷原隊列的消息辨泳,依次比對when的值,直到隊尾或者找到下一個消息的when值比msg的when值大的時候跳出循環(huán)玖院,將msg插到其中菠红,這個入隊的過程也就完成了,都是一些鏈表的基本操作难菌。之前也有說到试溯,因為每次有消息進(jìn)入mQueue,我們都是以這種方式來插入的扔傅,所以有序的消息隊列就是簡單以消息的when的大小來排序的耍共。消息插入到消息隊列完成后烫饼,判斷是否需要喚醒主線程猎塞,需要則調(diào)用native方法nativeWake()喚醒主線程來處理消息(Message msg = queue.next();//Looper.loop()方法中被喚醒后取出消息并分發(fā)處理
)。最后返回true表明消息插入隊列成功杠纵。這樣Message入隊的過程就算完成了荠耽,是不是挺簡單的~
以上,就是一個完整的消息傳遞和分發(fā)過程比藻。實際使用中铝量,我們用到更多的可能是handler.post(runnable);
,handler.postDelayed(runnable,delayMillis);
,view.postDelayed(runnable,delayMillis);
之類的方法,這些方法看上去好像沒有Message什么事银亲,但是點進(jìn)去一看就發(fā)現(xiàn)慢叨,這個被post的runnable就是Message的callback,簡單封裝一下就又走上了剛剛講完的消息傳遞路線务蝠,還沒反應(yīng)過來的回頭看看handler的dispatchMessage(Message msg)方法拍谐,因此這些方式我們都不用重寫handleMessage(Message msg)方法,使用起來非常方便。友情提示:非常方便的同時也非常容易導(dǎo)致內(nèi)存泄露馏段、空指針和其他一些狀態(tài)紊亂的錯誤(別問我怎么知道的轩拨,死過太多腦細(xì)胞??),慎用T合病M鋈亍!