Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 判斷當前是否為主執行緒的最可靠寫法

編輯: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 都被初始化了,但明顯是不同的物件。

原理: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;
    }
}

結論

三種情況都能解釋得通:

  • 主執行緒由 Android 運行環境呼叫 prepareMainLooper() 建立 Looper,並把引用存入 sMainLooper,因此 myLooper() 與 getMainLooper() 拿到的必然是同一個物件。
  • 沒有訊息迴圈的子執行緒,因為從未呼叫 prepare(),其 ThreadLocal 中沒有值,myLooper() 回傳 null。
  • 有訊息迴圈的子執行緒,prepare() 會建立一個屬於該執行緒的新 Looper,與主 Looper 是不同物件。

所以這個方法是可靠的,也不必擔心系統改名字。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved