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

Android 開發基礎:Main 執行緒向 Worker 執行緒發送訊息

編輯:關於 Android 程式設計

Android 中 UI 更新只能在主執行緒進行,而耗時工作要放在背景。兩者之間靠 Handler 與 Message 溝通。本文示範的是較少見但觀念上很關鍵的方向:由 Main 執行緒發訊息給 Worker 執行緒。

一、版面配置

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send"
        android:id="@+id/button" />

</RelativeLayout>

二、程式碼

private Button button;
private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) this.findViewById(R.id.button);
    button.setOnClickListener(new ButtonListener());

    WorkerThread thread = new WorkerThread();
    thread.start();
}

class ButtonListener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        Message msg = handler.obtainMessage();
        handler.sendMessage(msg);
    }
}

class WorkerThread extends Thread {
    public void run() {
        Looper.prepare();
        handler = new Handler() {
            public void handleMessage(Message msg) {
                System.out.println("Message From MainThread");
            }
        };
        Looper.loop();
    }
}

三、執行結果

每按一次按鈕,Worker 執行緒就會收到一個 Message 並印出對應文字。

關鍵觀念:Worker 執行緒預設沒有 Looper

這段程式最該記住的是 Looper.prepare() 與 Looper.loop() 這兩行。

主執行緒之所以能收訊息,是因為系統在啟動時已經幫它建好了 Looper。但我們自己 new Thread() 出來的執行緒是「裸」的,沒有 MessageQueue,直接 new Handler() 會拋出「Can't create handler inside thread that has not called Looper.prepare()」。

Looper.prepare() 的作用是建立 MessageQueue 並把它綁到當前執行緒;Looper.loop() 則是進入無限迴圈,持續從佇列取訊息交給對應的 Handler 處理。少了 loop(), prepare 出來的佇列不會有人消費,訊息永遠停在原地。

順帶一提,主執行緒之所以不用自己寫這兩行,是因為 ActivityThread.main() 內部已經做過了。它是全 App 唯一「天生就有 Looper」的執行緒。

實務上的兩點補充

第一,Handler 的宣告位置決定了它屬於哪個 Looper。範例把 handler 宣告在 WorkerThread 內部,所以它綁的是 Worker 的 Looper;若宣告在 Activity 層級,則綁主執行緒。這正是「同一個 Handler 類別,放哪裡就歸誰」的由來,也是初學者最容易搞混的地方。

第二,這種反向溝通在真實專案中並不常見。多數情境我們需要的是 Worker 算完回報給 Main 更新 UI,方向正好相反。之所以仍要理解它,是因為有些長時間執行的背景任務需要接受主執行緒的斷點指令,例如「暫停下載」「取消排程」,這時就得靠 Worker 自己的 Looper 來收命令。

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