Android 的 UI 只能在主執行緒(UI 執行緒)更新。若在工作執行緒中直接操作 view,會抛出:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
意思是:只有原始建立這個 view hierarchy 的執行緒才能修改它的 view。那麼該怎麼更新?最常見的兩種方式如下。
把更新 UI 的程式碼寫進 Runnable 交給它執行。運作機制是:如果呼叫時已在 UI 執行緒,就立即執行;否則把操作丟進 UI 執行緒的事件佇列排隊。
版面配置 activity_main.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="點擊更新界面" />
<TextView
android:id="@+id/input_str"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java:
package com.zsl.runonuithreaddemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView viewText = (TextView) findViewById(R.id.input_str);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
char[] str = "Android is intresting...".toCharArray();
viewText.setText(str, 0, str.length);
}
});
}
});
}
}
按下按鈕後,文字就被換成新的內容。
在 onCreate 中建立一個 Handler 實例,工作執行緒透過它送訊息,Handler 在主執行緒收到後更新 UI。這裡甚至有一個有趣的細節:Android 的 Handler 內部其實也是靠類似 runOnUiThread 的機制把 Runnable 丟回主執行緒的 Looper。
兩者的選擇:runOnUiThread 適合「偶爾更新一次」的簡單場景,程式碼最少;Handler 適合需要頻繁、有序、可延遲或可移除的訊息(例如每秒更新一次的計時器、進度條),因為它具備 Message、delayed message 與 removeCallbacks 這些能力。
除了這兩種,還有 View.post(Runnable)(不需要 Activity 參照,適合在自訂 View 或 Fragment 中使用)、AsyncTask 的 onProgressUpdate/onPostExecute,以及 Kotlin 的協程搭配 withContext(Dispatchers.Main)。現在的專案多半直接用後者,但理解 runOnUiThread 與 Handler 的原理,仍有助於看懂既有程式碼與除錯。
更多 Android 相關資訊可參考 Android 專題頁面。