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

關於 Handler 的六個思考:作用、UI 執行緒限制與常見異常

編輯:關於 Android 程式設計

把 Handler 的知識重新梳理一遍,本文涵蓋六個問題:

  1. Handler 的作用
  2. 為什麼 Android 設計成只能在 UI 執行緒更新 UI
  3. Handler 的兩個常見異常
  4. Handler、Looper、MessageQueue 的關係(源碼角度)
  5. HandlerThread(源碼角度)
  6. 主執行緒如何往子執行緒發訊息

一、Handler 的作用

歸納起來就兩件事:

  • 在非 UI 執行緒完成耗時操作,再回到 UI 執行緒更新畫面。
  • 在主執行緒中送出延遲訊息(sendMessageDelayed/postDelayed)。

二、為什麼只能主執行緒更新 UI

三個理由,重要性依序遞減:

  1. 解決多執行緒並發問題(根本原因)。UI 狀態若同時被多條執行緒改寫,畫面就會出現難以重現的錯亂。
  2. 提升效能。若為並發安全而到處加鎖,反而會造成 UI 卡頓。
  3. 架構更簡單。單一執行緒操作 UI,框架幫我們封裝掉大量同步細節。

你可能會想:既然是擔心並發,那我在子執行緒加鎖更新 UI 不就得了?實務上這麼做代價很高——鎖的範圍很難拿捏,稍不注意就是畫面掉幀甚至 ANR。

舉個類比:銀行取款的餘額不能變成負數。單執行緒時這個不變式自然成立;一旦多執行緒同時扣款而沒有適當的同步,就會出現「同一筆錢被領兩次」的資料競爭。UI 狀態也是同樣的道理。

三、兩個必須認得的異常

1. CalledFromWrongThreadException

原因:嘗試在子執行緒更新 UI。

2. Can't create handler inside thread that has not called Looper.prepare()

原因:在沒有 Looper 的子執行緒中建立 Handler。

先準備版面

<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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        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="按鈕" />

</RelativeLayout>

示範第一個異常:子執行緒更新 UI

public class MainActivity extends Activity {

    private TextView tv;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tv);
        btn = (Button) findViewById(R.id.btn);

        // 點擊按鈕後,嘗試在子執行緒中更新 UI
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("smyhvae");   // ← 這一行會丟異常
                    }
                }).start();
            }
        });
    }
}

核心就是最後那一行。按下按鈕,logcat 就會拋出 CalledFromWrongThreadException,訊息會明白告訴你「Only the original thread that created a view hierarchy can touch its views」。

正確寫法是把 setText 搬到 Handler 的 handleMessage 裡,由子執行緒 sendMessage 觸發。第二個異常則發生在你想於子執行緒中直接 new Handler 的時候——只要先 Looper.prepare() 再 Looper.loop(),或改用 HandlerThread 預先備好 Looper,就能避開。

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