下了7.0系統(tǒng)的源碼,打算要趕在過陰歷年之前雕欺,看一些東西岛马!不能再這么頹廢下去了!
早上又復(fù)習(xí)了Handler的運行流程屠列,看了源碼后啦逆,感覺和幾年前看的時候真是大不相同!
OK脸哀,不皮了蹦浦,進入正題!
嗯撞蜂,從ActivityThread開始吧盲镶!因為它是隱藏的,在你的IDE中是看不到的蝌诡!所以在你解壓系統(tǒng)源碼后的android-7.1.0_r1\frameworks\base\core\java\android\app這個目錄下溉贿,你可以找道這個文件!當(dāng)然浦旱,如果你覺得系統(tǒng)源碼有點大宇色,自己的網(wǎng)速有很爛下載不方便,你可以在這個網(wǎng)址在線看
在ActivityThread這個文件的末尾颁湖,你會看到一個main函數(shù)宣蠕,這個就是程序的入口了。
OK甥捺,功力有限抢蚀,其它的我們先不考慮,我們先來看我們能看的懂的镰禾。
看到 Looper.prepareMainLooper();//.......Looper.loop();應(yīng)該知道為啥我們可以在主線程中直接使用Handler了吧皿曲!哈哈..
我們看看Looper.prepareMainLooper();做了哪些操作唱逢。
這幾行英文注釋很簡單,大意呢就是屋休,android系統(tǒng)為創(chuàng)建了一個當(dāng)前線程的looper坞古,作為我們的application的主looper〗僬粒看到 我們熟悉的prepare(false);我們還是點進去瞅瞅
看仔細(xì)點痪枫,這是兩個方法,一個帶參數(shù)的毅哗,一個不帶參數(shù)的听怕,同樣的都是為我們Handler提供一個Looper的,帶參數(shù)的跟不帶參數(shù)有什么區(qū)別呢虑绵?嗯,還是看注釋闽烙,當(dāng)你的參數(shù)是true的時候翅睛,我們自己創(chuàng)建的looper會自動調(diào)用quit(),進行注銷操作,回到上面的Looper.prepareMainLooper()黑竞,它的方法體中傳的false捕发,也就是說,我們系統(tǒng)在創(chuàng)建主線程的Looper是不會自動銷毀的很魂,為什么要銷毀呢扎酷?下面我們看loop()方法體的時候,你就明白了遏匆!
我們接著看prepare(boolean quitAllowed)中的代碼法挨,sThreadLocal.get(),sThreadLocal是啥玩意幅聘,跟上去看看
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
直接實例化了凡纳,還是靜態(tài)的!點進去帝蒿,只有這么簡單的一行描述:
[圖片上傳失敗...(image-afd390-1514970145505)]
創(chuàng)建一個線程局部變量<雒印!emmm葛超,不太明白暴氏,那我們先跳過看它怎么給參數(shù)的:
sThreadLocal.set(new Looper(quitAllowed));
嗯,大概明白了绣张,sThreadLocal維護的是一個保存當(dāng)前運行線程變量信息的HashMap答渔!
它的get方法如下:
我們再捋一遍哈!當(dāng)執(zhí)行Loop的 prepare()方法的時候胖替,會判斷當(dāng)前的線程信息研儒,也就是為啥會拋出一個線程只允許創(chuàng)建一次prepare()的異常;
接著豫缨,如果當(dāng)前線程還沒prepare();,我們也就創(chuàng)建出了Looper的實例端朵,并將其塞入ThreadLocal
實例化這步中好芭,我們就為我們當(dāng)前的線程創(chuàng)建出了MessageQueue(消息隊列),并拿到當(dāng)前線程的各個信息冲呢!
OK舍败!至此,我們總算是搞清楚了Looper的實例化敬拓,是在prepare()邻薯,中完成,并且乘凸,并且,并且(重要的事情說三遍营勤!我們也創(chuàng)建出了當(dāng)前線程的一個消息循環(huán)器。
當(dāng)前線程的消息循環(huán)器創(chuàng)建好了葛作,但是我們還沒有啟動它!那怎么啟動呢赂蠢?
終于到Looper.loop();他就是啟動輪詢器的執(zhí)行方法體了!
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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.recycleUnchecked();
}
}
我們一行一行來吧玖院!
根據(jù)下面拋出的異常,我們應(yīng)該可以知道些什么量瓜!跳進去:
阿西吧司恳,這不就是prepare()的時候塞進去的那個Looper嘛!
final MessageQueue queue = me.mQueue;
這行不就是绍傲,Looper實例化創(chuàng)建的那個MessageQueue嘛
一個不可打斷的死for循環(huán)扔傅!無限循環(huán)的消息隊列是不是用Looper.loop();搞定了!
并且烫饼,我們是不是看到一個熟悉的方法調(diào)用猎塞?哈哈!
msg.target.dispatchMessage(msg);
是Handler的方法體吧8茏荨\ⅰ!
OK比藻,到這里铝量,當(dāng)前線程無限循環(huán)的消息隊列是創(chuàng)建成功了倘屹!
那么問題又來了?Handler是怎么把消息存到當(dāng)前線程無限循環(huán)的消息隊列呢慢叨?
默認(rèn)Handler實例化
this方法體:
看到執(zhí)行了EΤ住!拍谐!
mLooper = Looper.myLooper();//獲取當(dāng)前線程Looper
mQueue = mLooper.mQueue;//獲取當(dāng)前線程的消息隊列
OK烛缔,初始化完成,拿到當(dāng)前線程的Looper了轩拨,拿到了當(dāng)前線程Looper關(guān)聯(lián)的消息隊列mQueue.
再接著践瓷,我們發(fā)送一個最簡單的消息進行處理!
嗯亡蓉,接著走晕翠!
我們看一下這兩行代碼發(fā)生了什么!
Message msg = Message.obtain();
msg.what = what;
給的注釋說我們 從公共池中返回一個新的消息實例砍濒,讓我們避免在許多情況下分配新對象崖面。
解釋一下吧!上面多截出來的幾個變量很重要,sPool是一個全局的Message的索引甲棍,這也是就注釋的第一句話的意思感猛,當(dāng)前對象中如果存在Message對象奢赂,我們不需要創(chuàng)建新的實例對象膳灶,然后會將當(dāng)前Message的各個信息補充完整轧钓,它的next也是一個Message對象毕箍,我們會將當(dāng)前存在的Message對象生成一個新的Message節(jié)點而柑,就醬文捶!那如果沒有的話粹排,則返回一個新的new Message()恨搓,我們面試常問到的Handler綁定,也就是target的賦值常拓,還沒到弄抬,大家不要急掂恕!
回到Handler懊亡,我們接著往下走!
沒有什么有用的信息,接著往下走鸯两!
我們初始化Handler的時候mQueue,被賦給別人了匠襟!
接著走宅此!
來了父腕,此時將Handler附在Message上了!3饽选Q普铩镀裤!
接著看return queue.enqueueMessage(msg, uptimeMillis);
從字面理解暑劝,是將Message和執(zhí)行的時間點存入了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插入MessageQueue中,主要的幾行代碼貌嫡,我標(biāo)出來了衅枫!哈哈
其實沒什么可說的這個方法弦撩,主要是按照when(執(zhí)行時間點)來插入隊列中!當(dāng)沒有消息可插入的時候益楼,就會跳出這個循環(huán)感凤!
總結(jié):
實例化Handler(拿到當(dāng)前線程的Looper粒督,MessageQueue)屠橄,發(fā)送消息(將生成的攜帶Handler標(biāo)記的Message插入MessageQueue)闰挡,完成了消息的生成存儲流程长酗!之后的Looper.loop();方法就將開無限循環(huán)處理消息了夺脾!
這篇寫的有些簡陋咧叭,感覺主要是整個流程框架有點龐大復(fù)雜佳簸,整體的把握還是有些不足生均!這是我這邊的復(fù)習(xí)總結(jié)马胧!個人感覺吧佩脊,大家還是自己看看源碼比較好威彰!哈哈歇盼!話說回來豹缀,面試的時候這個問道的概率很大很大邢笙!掌握其中的各個關(guān)鍵點和整體的架構(gòu)把握很重要氮惯!
OK,據(jù)扯到這了债鸡!
每天進步一點點,時間會讓你成為巨人告唆!加油!