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

深入 ViewRoot:子線程到底能不能刷新 UI?

編輯:關於 Android 程式設計

自 Android 4.0 起,在子線程中直接更新 UI 會拋出 CalledFromWrongThreadException:「Only the original thread that created a view hierarchy can touch its views.」於是很多人得出結論——Android 子線程不能刷新 UI。這句話不能算錯,卻不夠嚴謹。真相是:線程能否刷新 UI,取決於 ViewRoot 是否屬於該線程。本文將從源碼層面徹底講清這件事。

一、異常從何而來

CalledFromWrongThreadException 由下面這段校驗代碼拋出:

void checkThread() {
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
    }
}

關鍵在於 mThread 是誰。翻開 ViewRoot 的構造函數,可以看到:

public ViewRoot(Context context) {
    // ...
    mThread = Thread.currentThread(); // 記錄創建 ViewRoot 的線程
    // ...
}

也就是說,mThread 保存的是創建這個 ViewRoot 的線程。而 UI 刷新時會一層層調用到 checkThread():

TextView.setText
  → TextView.checkForRelayout
    → View.invalidate
      → ViewGroup.invalidateChild
        → ViewRoot.invalidateChildInParent
          → ViewRoot.invalidateChild
            → ViewRoot.checkThread  // 若非創建線程,拋異常

二、子線程其實能刷新 UI

結論很清晰:只要某個線程擁有自己的 ViewRoot,它就能刷新 UI。問題是 ViewRoot 無法直接 new 出來。那怎麼辦?答案是通過 WindowManager.addView() 間接創建。看下面的例子:

class TestThread1 extends Thread {
    @Override
    public void run() {
        Looper.prepare();
        TextView tx = new TextView(MainActivity.this);
        tx.setText("test11111111111111111");

        WindowManager wm = MainActivity.this.getWindowManager();
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                250, 250, 200, 200,
                WindowManager.LayoutParams.FIRST_SUB_WINDOW,
                WindowManager.LayoutParams.TYPE_TOAST, PixelFormat.OPAQUE);
        wm.addView(tx, params); // 這裡會創建 ViewRoot
        Looper.loop();
    }
}

運行後你會發現,屏幕上真的出現了「test11111111111111111」。

秘密就在 wm.addView(tx, params)。追進 WindowManagerImpl.addView:

private void addView(View view, ViewGroup.LayoutParams params, boolean nest) {
    // ...
    ViewRoot root;
    // ...
    root = new ViewRoot(view.getContext()); // 在當前線程創建 ViewRoot
    root.mAddNesting = 1;
    view.setLayoutParams(wparams);
    // ...
    root.setView(view, wparams, panelParentView);
}

因為這個 ViewRoot 是在 TestThread1 中創建的,所以它的 mThread 就是 TestThread1,後續由該線程刷新 UI 自然不會報錯。

三、那為什麼有的子線程刷新又能「僥倖成功」?

這裡有個容易讓人困惑的現象:有時在 onCreate 裡開子線程直接 btn.setText() 居然沒報錯,文本還改了。難道子線程真的能刷主線程的 UI?

class TestThread2 extends Thread {
    Button btn;
    public TestThread2(Button btn) { this.btn = btn; }
    @Override
    public void run() {
        btn.setText("TestThread2.run");
    }
}

真相藏在 ViewRoot 的創建時機裡。ViewRoot 是在 ActivityThread.handleResumeActivity() 中創建的:

final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward) {
    // ...
    if (r.window == null && !a.mFinished && willBeVisible) {
        r.window = r.activity.getWindow();
        View decor = r.window.getDecorView();
        // ...
        wm.addView(decor, l); // 此時才創建 ViewRoot
    }
    // ...
}

也就是說,在 onResume 之前,ViewRoot 尚未建立,自然沒有 checkThread 校驗。所以子線程在這個階段 setText,文本被暫存了下來;等真正 resume、ViewRoot 建立並刷新界面時,就把之前設定的「TestThread2.run」刷了出來,造成「子線程能改 UI」的假象。

四、切記生命周期的坑

注意:這種僥倖只在 onCreate → onStart → onResume 首次啟動過程中有效。而在 onPause → onRestart → onStart 的復用過程中,ViewRoot 早已存在,此時子線程刷新 UI 就會老老實實地拋出異常。

所以,結論是:子線程並非絕對不能刷新 UI,關鍵在於它是否持有對應的 ViewRoot。但為了代碼的健壯性與可維護性,我們仍強烈建議通過 Handler、runOnUiThread 或 View.post 等方式,把 UI 更新統一交給主線程處理——這才是安全、可靠的正道。

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