前言
Handler是我們?nèi)粘i_(kāi)發(fā)中經(jīng)常要用到的,不管你是新手還是老鳥(niǎo)。剛?cè)胄械娜丝赡軆H僅知道點(diǎn)用Handler來(lái)更新UI等等。記得剛畢業(yè)的時(shí)候,第一次會(huì)用Handler實(shí)現(xiàn)了UI的更新,之后的時(shí)間對(duì)Handler的認(rèn)識(shí)也僅僅是停留在表面功夫,大部分都是臨時(shí)抱佛腳,碰到問(wèn)題才想到要去研究源碼。
有時(shí)候想想,學(xué)習(xí)動(dòng)力真的很重要!如果你浮在表面,覺(jué)得自己知道怎么用api了,就沾沾自喜,那樣永遠(yuǎn)都不會(huì)進(jìn)步。這個(gè)時(shí)候就是考驗(yàn)自己的時(shí)候了,當(dāng)你沉下心來(lái),一段源碼一段源碼的去扣,直到理解為止,在閱讀源碼的過(guò)程中你的思維能力也得到了一次鍛煉,我相信,你對(duì)這部分知識(shí)的理解也會(huì)更加透徹。
拋出我們今天的問(wèn)題:為什么在子線程中執(zhí)行 new Handler() 會(huì)拋出異常?我們先來(lái)看看一個(gè)小栗子:
new Thread(new Runnable() {
@Override
public void run() {
new Handler(){
@Override
public void handleMessage (Message message){
super.handleMessage(message);
}
};
}
},"ThreadOne").start();
運(yùn)行一下代碼,發(fā)現(xiàn)程序出現(xiàn)了如下異常:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:204)
at android.os.Handler.<init>(Handler.java:118)
at com.example.bthvi.myconstrainlayoutapplication.MainActivity$1$1.<init>(MainActivity.java:21)
at com.example.bthvi.myconstrainlayoutapplication.MainActivity$1.run(MainActivity.java:21)
at java.lang.Thread.run(Thread.java:764)
嗯,這就是我們今天要討論的問(wèn)題:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(),大致的意思是無(wú)法在未調(diào)用looperation .prepare()的線程中創(chuàng)建handler,要找到原因,從Handler的構(gòu)造方法開(kāi)始。
Handler構(gòu)造方法
當(dāng)我們new Handler()的時(shí)候,最終調(diào)用了Handler的以下方法
/**
* 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());
}
}
// 標(biāo)記1
mLooper = Looper.myLooper();
if (mLooper == null) {
// 標(biāo)記2
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
翻譯一下這段注釋?zhuān)耗J(rèn)的構(gòu)造函數(shù)將handler和當(dāng)前線程所持有的Looper關(guān)聯(lián)在一起,沒(méi)有當(dāng)前線程沒(méi)有Looper對(duì)象,handler就無(wú)法接收消息,異常也就被拋出了。我們接在往下看,if判斷語(yǔ)句里的boolean型變量默認(rèn)值為false,所以里面的邏輯暫時(shí)先不看。接下來(lái)程序走到了 標(biāo)記1所對(duì)應(yīng)的語(yǔ)句處,我們看一下源碼:
/**
* 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();
}
看一下注釋?zhuān)笾碌囊馑际欠祷嘏c當(dāng)前thread相關(guān)聯(lián)的Looper對(duì)象,如果當(dāng)前thread沒(méi)有關(guān)聯(lián)的Looper那就返回null。 我們直接看sThreadLocal.get()源碼:
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
該方法第二行調(diào)用了getMap(t)方法,我們來(lái)看看getMap(t)的源碼:
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
getMap(t)返回一個(gè)ThreadLocalMap對(duì)象,這個(gè)對(duì)象是什么時(shí)候創(chuàng)建的呢? 在以上的幾個(gè)步驟中我們沒(méi)有發(fā)現(xiàn)創(chuàng)建該對(duì)象的過(guò)程..
我們回到標(biāo)記1和標(biāo)記2處,標(biāo)記1獲取到mLooper后,緊接著標(biāo)記2處對(duì)mLooper做了非空判斷,而此時(shí)程序拋了異常,說(shuō)明mLooper是null,回到getMap(t)這里,好像并不能找出什么重要的線索。
換個(gè)角度想一想,異常信息提示我們應(yīng)該要調(diào)用 Looper.prepare(),那我們先去Looper的prepare方法里找找線索。
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) { // 標(biāo)記3
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
我們看看這個(gè)帶參數(shù)的prepare方法,標(biāo)記3處判斷sThreadLocal.get()是否不等于null,當(dāng)我們第一次調(diào)用Looper.prepare()時(shí),sThreadLocal.get()一定為null,為什么這么說(shuō)呢? 因?yàn)樵撝挡粸榭盏脑?,那么?biāo)記1處所獲取到的對(duì)象也不會(huì)為空,也就不會(huì)拋出異常!所以第一次進(jìn)來(lái)肯定是null,第二次進(jìn)來(lái)的話就不是null了,拋出了異常"Only one Looper may be created per thread",也說(shuō)明了在子線程中只能調(diào)用Looper.prepare()一次。所以我們看看 sThreadLocal.set(new Looper(quitAllowed))做了哪些操作。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
往set(T value)中傳入了一個(gè) Looper對(duì)象,set()方法里第二行還是調(diào)用了 getMap(t),由于是第一次進(jìn)來(lái)返回map==null,我們看看 createMap(t, value) :
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
可以看到執(zhí)行到這里的時(shí)候,才對(duì)當(dāng)前線程的threadLocals進(jìn)行了賦值,ThreadLocalMap以當(dāng)前線程為 key,以Looper為值進(jìn)行存儲(chǔ)。
做一個(gè)總結(jié),回到Looper.myLooper()這里:
/**
* 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();
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
當(dāng)我們沒(méi)有調(diào)用Looper.prepare()時(shí),當(dāng)前thread的threadLocals還沒(méi)有創(chuàng)建,getMap()返回為null,get()方法執(zhí)行到了setInitialValue()這里:
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
protected T initialValue() {
return null;
}
可以明顯的看到,setInitialValue()返回的值是固定的就是null。setInitialValue返回null,也就是get()返回null,接著myLooper()返回null,程序也就拋出了異常!
分析完源碼,也不難做出結(jié)論,一個(gè)線程只能有一個(gè)looper對(duì)象,這個(gè)looper會(huì)以Map形式存儲(chǔ)在儲(chǔ)在當(dāng)前線程的ThreadLocal中。