Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android Handler 消息機制 thoroughly 解析

Handler 的主要作用

1. 在新建的執行緒中發送消息
2. 在主執行緒中取得並處理消息

為什麼需要這套機制

Android 的 UI 操作並非執行緒安全,多執行緒同時操作同一個元件可能導致嚴重問題。因此系統規定:只有 UI 執行緒能修改 UI 元件屬性,也就是單執行緒模型。但這也帶來副作用——若在 UI 執行緒做耗時運算,畫面就會卡住甚至觸發 ANR(約 20 秒未完成即強制關閉)。所以當背景執行緒需要更新介面時,就必須借助 Handler 把消息丟回 UI 執行緒。

Handler 的常用方法

1. void handleMessage(Message msg):處理消息,通常會被覆寫
2. final boolean hasMessage(int what):檢查佇列中是否有 what 相符的消息
3. final boolean hasMessage(int what, Object object):再比對 object
4. sendEmptyMessage(int what):發送空消息
5. final boolean sendEmptyMessageDelayed(int what, long delayMillis):延遲發送空消息
6. final boolean sendMessage(Message msg):立即發送
7. final boolean sendMessageDelayed(Message msg, long delayMillis):延遲發送

協同工作的三個元件

Handler:把消息交給 Looper 管理的 MessageQueue,並負責處理 Looper 派回來的消息
MessageQueue:以先進先出的方式管理 Message
Looper:每個執行緒只有一個,UI 執行緒由系統預先建立,它不斷從 MessageQueue 取消息並分派給對應的 Handler

在自訂執行緒中使用 Handler 的三步

1. 呼叫 Looper.prepare() 為當前執行緒建立 Looper,其建構子會自動建立對應的 MessageQueue
2. 建立 Handler 子類實例並覆寫 handleMessage()
3. 呼叫 Looper.loop() 啟動迴圈

注意 prepare 與 loop 必須成對出現,且同一個執行緒只能 prepare 一次,否則會丟出 RuntimeException。

版面配置示例

<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" >
  <EditText
    android:id="@+id/ed1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number" />
  <Button
    android:id="@+id/Ok"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/ed1"
    android:text="@string/Ok" />
  <Button
    android:id="@+id/next"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/Ok"
    android:text="下一張" />
  <ImageView
    android:id="@+id/image1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/next"
    android:src="@drawable/a3" />
</RelativeLayout>

實作時讓背景執行緒下載圖片,完成後用 Handler 送一則消息,在 handleMessage 裡設定 ImageView 的 src,就能避免跨執行緒直接操作 View 而崩潰。

Copyright © Linux教程網 All Rights Reserved