編輯:關於 Android 程式設計
要在 Android 中判斷某個線程是否為主線程,你可能會想到直接比對線程名稱。這固然可行,但真的夠可靠嗎?萬一哪天 Google 把主線程的名字改掉,判斷就失效了。本文提供一個更穩健的方案,並深入探討其背後原理。
最可靠的做法是比對 Looper:
public static boolean isInMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
寫到這裡其實已解決標題的問題,但僅止於此未免太淺。我們不妨再往下挖。
為方便觀察,我們加上一些偵錯輸出:
private boolean isInMainThread() {
Looper myLooper = Looper.myLooper();
Looper mainLooper = Looper.getMainLooper();
Log.i(LOGTAG, "isInMainThread myLooper=" + myLooper + ";mainLooper=" + mainLooper);
return myLooper == mainLooper;
}
實驗一:在主線程中呼叫
Log.i(LOGTAG, "testInMainThread inMainThread=" + isInMainThread());
輸出:
I/TestInMainThread(32028): isInMainThread myLooper=Looper{40d35ef8};mainLooper=Looper{40d35ef8}
I/TestInMainThread(32028): testInMainThread inMainThread=true
兩個 Looper 是同一個物件,驗證通過。
實驗二:在沒有消息循環的非主線程中
new Thread() {
@Override
public void run() {
Log.i(LOGTAG, "testIn NOT in MainThread isMainThread=" + isInMainThread());
super.run();
}
}.start();
輸出:
I/TestInMainThread(32028): isInMainThread myLooper=null;mainLooper=Looper{40d35ef8}
I/TestInMainThread(32028): testIn NOT in MainThread isMainThread=false
此時新建線程的 Looper 是 null,因為 Android 中的線程預設並未綁定消息循環。
實驗三:在綁定了消息循環的線程中
new Thread() {
private Handler mHandler;
@Override
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Log.i(LOGTAG, "testInNonMainLooperThread isMainThread=" + isInMainThread());
Looper.loop();
}
}.start();
輸出:
I/TestInMainThread(32028): isInMainThread myLooper=Looper{40d72c58};mainLooper=Looper{40d35ef8}
I/TestInMainThread(32028): testInNonMainLooperThread isMainThread=false
兩個 Looper 都被初始化了,但彼此是不同的物件。
這一切奧秘都藏在 Looper 的源碼裡:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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));
}
public static Looper myLooper() {
return sThreadLocal.get();
}
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
重點在於:對主線程而言,prepareMainLooper() 由 Android 執行環境呼叫(而非開發者顯式呼叫),它建立主線程的 Looper 並把引用交給 sMainLooper,因此主線程的 myLooper() 與 getMainLooper() 取到的是同一個引用。
而沒有消息循環的一般線程,由於從未呼叫 prepare(),其 Looper 恆為 null,自然與主線程不同。至於已呼叫 Looper.prepare() 綁定消息循環的線程,會建立屬於自己的新 Looper,也不可能與主線程相同。
綜上所述,用 Looper.myLooper() == Looper.getMainLooper() 來判斷主線程,是既可靠又優雅的做法。
Android 自定義 Adapter 打造 ListView 的思路與完整程式碼
在開發中,我們經常使用 ListView 這個控制項。Android API 也提供了許多建立適配器的快捷方式,例如 ArrayAdapter、SimpleAdapter
ImageView 圖像控件詳解(上):屬性辨析與縮放模式
(一)概述 ImageView 是最基礎的圖像顯示控件,除了展示圖片,還支持放大、縮小、旋轉等操作。本篇先把它的幾個核心屬性掰扯清楚。 (二)src 與 backgro
Eclipse 正確匯入 Android 專案的方法與常見錯誤排除
直接看圖: 匯入專案後套件出現錯誤的解決方法 選中專案,右鍵開啟 Properties,依序檢查: 檢查 android 頁面中是否勾選了 project buil
Activity啟動過程源碼分析:從startActivity到系統回調
分析源碼的文章總顯得有些繁瑣枯燥,但把看源碼時的心得整理出來,本身就是一種提升。這篇筆記分析Activity的啟動流程,我會盡量講得直白一些。個人認為看源碼不宜鑽得太細,