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

Android Handler 的實際用法:讓子線程安全更新 UI

編輯:關於 Android 程式設計

Android 只允許在主線程(UI 線程)操作介面。因此當有耗時工作時,必須丟到子線程執行,再把結果「送回」主線程更新畫面——這正是 Handler 存在的意義。若主線程超過約 5 秒仍未回應,系統就會跳出「強制關閉」的對話框,所以這個機制並非可有可無的裝飾。

一、布局檔

<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" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="@string/description" />
</RelativeLayout>

二、主要程式碼

子線程隨機挑一張圖,透過 Message 通知 Handler;Handler 可以同時處理多個子線程的訊息,用 what 欄位區分。

public class MainActivity extends Activity {

    private static final int UPDATE_PIC = 0x100;
    private static final int UPDATE_DATA = 0x101;

    private ImageView imageView = null;
    private MyHandler handler = null;
    private UpdateThread updateThread = null;

    private int[] path = new int[] {
        R.drawable.psb1, R.drawable.psb2, R.drawable.psb3,
        R.drawable.psb4, R.drawable.psb5, R.drawable.psb6 };
    private String[] names;

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

        names = getResources().getStringArray(R.array.arrays);
        imageView = (ImageView) findViewById(R.id.imageView);
        handler = new MyHandler();

        new Thread(new myThread()).start();
        updateThread = new UpdateThread();
        handler.post(updateThread);
    }

    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == UPDATE_PIC) {
                imageView.setImageResource(path[msg.arg1]);
                setTitle(msg.getData().getString("name"));
            } else if (msg.what == UPDATE_DATA) {
                System.out.println("data = " + msg.arg1);
            } else {
                super.handleMessage(msg);
            }
        }
    }

    private class myThread implements Runnable {
        @Override
        public void run() {
            int index = 0;
            while (!Thread.currentThread().isInterrupted()) {
                index = new Random().nextInt(path.length);
                Message message = handler.obtainMessage();
                message.arg1 = index;              // 用 arg1/arg2 傳值,資源消耗最少
                message.what = UPDATE_PIC;
                Bundle bundle = new Bundle();
                bundle.putString("name", names[index]);
                message.setData(bundle);
                handler.sendMessage(message);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private class UpdateThread implements Runnable {
        int index = 0;

        @Override
        public void run() {
            index++;
            Message message = handler.obtainMessage();
            message.arg1 = index;
            message.what = UPDATE_DATA;
            handler.sendMessage(message);
            handler.postDelayed(updateThread, 3000);
        }
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(updateThread);
        super.onDestroy();
    }
}

關鍵觀念

  • Message 的傳值方式:優先使用 arg1、arg2 傳整數,資料量大時才用 Bundle(setData()),這樣對系統資源最友善。
  • what 作為分派依據:一個 Handler 可以服務多種任務,用 what 辨識來源與意圖。
  • obtainMessage():從訊息池取用而非每次 new,能減少 GC 壓力。
  • 記得善後:在 onDestroy() 呼叫 removeCallbacks(),避免 Activity 已銷毀卻仍收到延遲訊息而導致記憶體配置或崩潰。
  • post 與 sendMessage 的差別:前者送的是 Runnable,後者送的是 Message;延遲執行則分別用 postDelayed() 與 sendMessageDelayed()。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved