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

HandlerThread:自帶 Looper 的工作執行緒

編輯:關於 Android 程式設計

前面談到 Handler 的運作機制時,示範了如何在普通執行緒中手動產生 Looper 並用 Handler 通訊。但普通執行緒預設沒有 Looper,每次都要自己 Looper.prepare()、Looper.loop() 顯得很麻煩。Android 已經封裝好了這個模式——HandlerThread。

一、原始碼

public class HandlerThread extends Thread {
    private int mPriority;
    private int mTid = -1;
    private Looper mLooper;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }

    protected void onLooperPrepared() {
    }

    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

    public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }
        // 若執行緒已啟動,等到 looper 建立完成
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }

    public int getThreadId() {
        return mTid;
    }
}

可以看到它就是繼承 Thread,在 run() 裡做 Looper.prepare() 與 Looper.loop(),再透過 synchronized + wait/notifyAll 確保 getLooper() 不會在 Looper 建立完成前回傳 null。

使用時一定要注意:必須呼叫 start(),否則 run() 不會被執行,Handler 機制也就建立不起來,getLooper() 會永遠卡在 wait。

二、經典應用:在 Service 中做背景任務

HandlerThread 最常見的用法就是搭配 Service。一般而言 Service 運行在主執行緒,如果直接在裡面做耗時工作就會阻塞 UI。標準解法是:Service 建立一個 HandlerThread,把任務丟給它。

public class BackService extends Service {

    private ServiceHandler serviceHandler;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            onHandleIntent((Intent) msg.obj);
            // 只有在 startId 與最後啟動該 service 時產生的 ID 相等時才停止服務
            stopSelf(msg.arg1);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HandlerThread thread = new HandlerThread("BackService");
        thread.start();
        Looper serviceLooper = thread.getLooper();
        serviceHandler = new ServiceHandler(serviceLooper);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Message msg = serviceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        serviceHandler.sendMessage(msg);
        return super.onStartCommand(intent, flags, startId);
    }

    protected void onHandleIntent(Intent intent) {
        // 在這裡做你的非同步任務
    }
}

三、stopSelf(startId) 的巧妙之處

這個設計值得細看。服務可能被連續啟動五次,產生五個訊息。如果用無參數的 stopSelf(),第一個任務跑完就會關掉服務,後面四個任務全部丟失。

把 startId 塞進 msg.arg1,然後呼叫 stopSelf(msg.arg1),系統會比對:如果還有更新的啟動請求是未完成的,就不真的關閉。這樣就實現了「所有排隊任務都跑完才收工」的行為。

四、其實 IntentService 就是這個模式的官方版

把上面的程式碼和 IntentService 對照,你會發現它們幾乎一模一樣——IntentService 內部做的就是建立 HandlerThread、用 Looper 建構 Handler、在 handleMessage() 裡回呼 onHandleIntent(),並用 startId 控管關閉時機。

所以實務上的建議是:除非你需要客製化處理邏輯(例如優先權調整、中途取消、動態改執行緒數),否則直接用 IntentService 就好。另外提醒一點,stopSelf(int) 這個 API 在較新的 Android 版本已被標記為不建議使用,新專案建議改用 WorkManager。

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