前言
Handler是我們?nèi)粘i_發(fā)中經(jīng)常要用到的,不管你是新手還是老鳥。剛?cè)胄械娜丝赡軆H僅知道點用Handler來更新UI等等。記得剛畢業(yè)的時候,第一次會用Handler實現(xiàn)了UI的更新,之后的時間對Handler的認識也僅僅是停留在表面功夫,大部分都是臨時抱佛腳,碰到問題才想到要去研究源碼。
有時候想想,學(xué)習動力真的很重要!如果你浮在表面,覺得自己知道怎么用api了,就沾沾自喜,那樣永遠都不會進步。這個時候就是考驗自己的時候了,當你沉下心來,一段源碼一段源碼的去扣,直到理解為止,在閱讀源碼的過程中你的思維能力也得到了一次鍛煉,我相信,你對這部分知識的理解也會更加透徹。
拋出我們今天的問題:為什么在子線程中執(zhí)行 new Handler() 會拋出異常?我們先來看看一個小栗子:
new Thread(new Runnable() {
@Override
public void run() {
new Handler(){
@Override
public void handleMessage (Message message){
super.handleMessage(message);
}
};
}
},"ThreadOne").start();
運行一下代碼,發(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)
嗯,這就是我們今天要討論的問題:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(),大致的意思是無法在未調(diào)用looperation .prepare()的線程中創(chuàng)建handler,要找到原因,從Handler的構(gòu)造方法開始。
Handler構(gòu)造方法
當我們new Handler()的時候,最終調(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());
}
}
// 標記1
mLooper = Looper.myLooper();
if (mLooper == null) {
// 標記2
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
翻譯一下這段注釋:默認的構(gòu)造函數(shù)將handler和當前線程所持有的Looper關(guān)聯(lián)在一起,沒有當前線程沒有Looper對象,handler就無法接收消息,異常也就被拋出了。我們接在往下看,if判斷語句里的boolean型變量默認值為false,所以里面的邏輯暫時先不看。接下來程序走到了 標記1所對應(yīng)的語句處,我們看一下源碼:
/**
* 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();
}
看一下注釋,大致的意思是返回與當前thread相關(guān)聯(lián)的Looper對象,如果當前thread沒有關(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)方法,我們來看看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)返回一個ThreadLocalMap對象,這個對象是什么時候創(chuàng)建的呢? 在以上的幾個步驟中我們沒有發(fā)現(xiàn)創(chuàng)建該對象的過程..
我們回到標記1和標記2處,標記1獲取到mLooper后,緊接著標記2處對mLooper做了非空判斷,而此時程序拋了異常,說明mLooper是null,回到getMap(t)這里,好像并不能找出什么重要的線索。
換個角度想一想,異常信息提示我們應(yīng)該要調(diào)用 Looper.prepare(),那我們先去Looper的prepare方法里找找線索。
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) { // 標記3
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
我們看看這個帶參數(shù)的prepare方法,標記3處判斷sThreadLocal.get()是否不等于null,當我們第一次調(diào)用Looper.prepare()時,sThreadLocal.get()一定為null,為什么這么說呢? 因為該值不為空的話,那么標記1處所獲取到的對象也不會為空,也就不會拋出異常!所以第一次進來肯定是null,第二次進來的話就不是null了,拋出了異常"Only one Looper may be created per thread",也說明了在子線程中只能調(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)中傳入了一個 Looper對象,set()方法里第二行還是調(diào)用了 getMap(t),由于是第一次進來返回map==null,我們看看 createMap(t, value) :
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
可以看到執(zhí)行到這里的時候,才對當前線程的threadLocals進行了賦值,ThreadLocalMap以當前線程為 key,以Looper為值進行存儲。
做一個總結(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;
}
當我們沒有調(diào)用Looper.prepare()時,當前thread的threadLocals還沒有創(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é)論,一個線程只能有一個looper對象,這個looper會以Map形式存儲在儲在當前線程的ThreadLocal中。