編輯:Android 開發實例
要在 Android 中判斷某段程式碼是否跑在主執行緒,你可能會想到「比對執行緒名稱」。這招確實能解決問題,但它可靠嗎?萬一某個版本系統改了執行緒名稱,判斷就整套失效了。
public static boolean isInMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
用 Looper 物件身分比對,而不是依賴字串,這才是穩健的做法。不過若只停在這裡未免太淺,我們不妨往下挖一層,看看它為什麼永遠成立。
加上一點除錯輸出:
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
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 早已初始化,而我們新建的執行緒的 Looper 是 null——因為 Android 中的執行緒預設並沒有綁定訊息迴圈。
依照官方文件的標準寫法,用 Looper.prepare() 與 Looper.loop() 建立綁定 Looper 的執行緒:
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 都被初始化了,但明顯是不同的物件。
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
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));
}
/**
* Return the Looper object associated with the current thread.
* Returns null if the calling thread is not associated with a Looper.
*/
public static Looper myLooper() {
return sThreadLocal.get();
}
/** Returns the application's main looper, which lives in the main thread of the application. */
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
三種情況都能解釋得通:
prepareMainLooper() 建立 Looper,並把引用存入 sMainLooper,因此 myLooper() 與 getMainLooper() 拿到的必然是同一個物件。prepare(),其 ThreadLocal 中沒有值,myLooper() 回傳 null。prepare() 會建立一個屬於該執行緒的新 Looper,與主 Looper 是不同物件。所以這個方法是可靠的,也不必擔心系統改名字。
Android 手機衛士(十一):自訂焦點 TextView 實作跑馬燈
跑馬燈效果原理在 Android 中,TextView 要出現跑馬燈效果,通常需要單行顯示、設定 ellipsize 為 marquee,並讓元件取得焦點。若焦點不定時被
Android 登入實作:帳號密碼驗證與三次錯誤鎖定
登入畫面負責向使用者索取帳號與密碼以驗證身分,是許多應用(如 Facebook、微博)的必備環節。本章說明如何建立登入介面,並處理安全性與錯誤嘗試次數的限制。 首先在版
Android 本地化實戰:用資源限定符自動切換語言
Android App 可能同時被台灣、日本、德國的使用者安裝使用。若介面文字硬寫在程式碼或版面檔中,就永遠只能呈現一種語言。本地化要做的,是把這些文字抽成資源,並依裝置
動手做一個 Android 音樂播放器:Service + MediaPlayer + 廣播的完整實作
先看一下我們要做出來的清爽介面: 如果只用 Activity 來做這種東西那就太簡單了——播放必須在離開介面後持續進行,所以我們用的是 Service。 設計思路 動