從上面的文章中我們已經(jīng)知道了Handler,MessageQuene,Message的源碼,Looper也看了loop方法,但是我們還漏調(diào)了Looper.prepare()方法,好那我們就來看這個源碼:

構(gòu)造方法是私有的所以我們不能直接new,那我們怎么創(chuàng)建一個Looper對象呢?
/**
* 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();
}
從threadLocal中獲取looper,并且有可能返回空,返回空的情況一般為在異步線程中沒有調(diào)用Looper.prepare()。ThreadLocal到底是個神馬東西,大概意思是這樣子的:
ThreadLocal的作用是提供線程內(nèi)的局部變量,這種變量在線程的生命周期內(nèi)起作用,減少同一個線程內(nèi)多個函數(shù)或者組件之間一些公共變量的傳遞的復(fù)雜度。以后章節(jié)會詳細(xì)介紹。在這里只需要記住用這個來保證一個線程只有一個Looper繼而保證只有一個消息隊列。
接下來我們再來看另外一個prepare()方法:
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
可以看出如果當(dāng)前獲取的Looper為空會報錯。這樣也保證一個線程只有一個Looper繼而保證只有一個MessageQuene。好了源碼就講到這兒,我們最后通過一個完整的圖來整理源碼中的知識點(diǎn)

image.png

image.png