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

Android 基本功:IntentService 的用法與適用場景

編輯:關於 Android 程式設計

IntentService 是 Service 的子類,在原本的基礎上補上了執行緒與佇列的處理。要理解它的價值,得先看 Service 本身有兩個先天限制:

  • Service 不會另開行程:它與所屬應用位於同一個行程、同一條主執行緒;
  • Service 也不是一條新執行緒:因此在 Service 裡直接跑耗時任務,會卡住 UI 並可能引發 ANR。

結果就是:開發者想在背景做事,卻得自己在 Service 裡開 thread、自己管理生命週期、自己處理同步。IntentService 把這一切收攏起來了。

IntentService 的五個特性

  • 會建立獨立的 worker 執行緒來處理所有 Intent 請求;
  • onHandleIntent() 在這條 worker 執行緒上被呼叫,無需自己處理多執行緒問題;
  • 所有請求處理完畢後會自動停止,不必呼叫 stopSelf();
  • 為 onBind() 提供預設實作,回傳 null;
  • 為 onStartCommand() 提供預設實作,負責把請求 Intent 加入佇列。

換句話說,IntentService 就是「序列化的背景工作佇列」:每個 Intent 代表一項工作,依送出的先後順序逐一執行,全部做完就自己收工。

使用步驟

只有兩步:繼承 IntentService,並重寫 onHandleIntent()。

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");   // 建構子必須呼叫 super(名字)
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // 這裡已在獨立的 worker 執行緒上,可安全執行耗時任務
        long endTime = System.currentTimeMillis() + 20 * 1000;
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.d(TAG, "----耗時任務執行完成---");
    }
}

觸發的方式與普通 Service 完全一樣:

public void startIntentService(View source) {
    Intent intent = new Intent(this, MyIntentService.class);
    startService(intent);   // 可連續呼叫多次,會排入佇列
}

别忘了在 AndroidManifest 中註冊這個 Service,漏了會直接 IllegalArgumentException。

對照:普通 Service 會發生什麼事

public class MyService extends Service {

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 在這裡跑耗時任務會導致 ANR(Application Not Responding)
        long endTime = System.currentTimeMillis() + 20 * 1000;
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return START_STICKY;
    }
}

把同樣的邏輯搬進 onStartCommand(),因為它跑在主執行緒上,畫面會直接凍住,五秒後系統跳出 ANR 對話框。這段對照最能說明 IntentService 存在的意義:它把「背景執行」這件事從開發者的責任變成平台的保證。

實務上的選擇建議

IntentService 適合的是「一次性的、可序列化的、不需要使用者即時回饋」的工作,例如上報日誌、同步一筆資料、處理相機回傳的圖片。

但它有兩個明顯的侷限:所有工作只能順序執行,無法併發;而且工作進行中若 App 被系統回收,任務就會中斷,因為它終究只是一個 Service,沒有任何持久化保證。

因此,若是在較新的專案上開發,更合適的選擇是 WorkManager:它同樣提供佇列與序列化,但多了約束條件(只在有網路時執行)、可觀測狀態、以及跨重啟的持久化。IntentService 在 API 30 已被標記為 deprecated,理解它的設計仍然有價值——WorkManager 的很多概念就是從這裡長出來的。

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