Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 判斷當前是否為主線程的最可靠方法

編輯:關於 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() 來判斷主線程,是既可靠又優雅的做法。

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