編輯:關於 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 // 若非創建線程,拋異常
結論很清晰:只要某個線程擁有自己的 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 更新統一交給主線程處理——這才是安全、可靠的正道。
深入 Android View 容器:ViewGroup 源碼解析與事件分發
為什麼要讀 ViewGroup 源碼? 若想真正掌握 Android 的自訂元件,不能只停留在會用 LinearLayout、RelativeLayout 或 Frame
ScrollView 裡塞 ListView 只剩一行?破解嵌套滑動衝突
ScrollView 和 ListView 大家都不陌生,但這兩個東西湊在一起就容易出狀況。舉例來說,如果我們想在列表下方再放一些額外的控制項,並希望它們跟著一起滑動,最
Android 手勢識別:GestureOverlayView 與手勢庫
手勢識別在 Android 中並不如點擊、滑動那樣常見,但在一些特殊場景中仍然非常有趣。例如密碼手勢、繪圖簽名或快捷操作。Android 提供了 GestureOverl
Android 中使用 RecyclerView 實現下拉刷新和上拉加載
為 RecyclerView 實作下拉刷新與上拉加載,可以善用成熟開源庫,而不必從零打造手勢與動畫。常見方案是使用 Ultra-Pull-To-Refresh 提供的 P