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

Android 面試常考題:IntentService 的原理與實戰

編輯:關於 Android 程式設計

開發時常會遇到這類需求:一個任務被拆成好幾個子任務,必須按順序執行,全部跑完這件任務才算完成。

用幾個子執行緒接力當然做得到,但每條執行緒都得手動控制,前一個跑完才開下一個;或者乾脆全塞進同一條執行緒裡順序跑。這些寫法都可行,可是如果這是一項背景工作,就必須放進 Service。而 Service 與 Activity 同級,要做耗時運算就得自己在 Service 裡開子執行緒——麻煩。

有沒有更省事的做法?有,就是 IntentService。

IntentService 是什麼

IntentService 繼承自 Service,專門用來處理非同步請求。它內部自帶一條工作執行緒負責跑耗時操作,啟動方式與傳統 Service 完全相同;而任務跑完之後,它會自己停止,不需要你手動 stopService 或 stopSelf。

你可以啟動它很多次,每一個請求會以工作佇列的形式,在 onHandleIntent() 回呼中被逐一處理。同一時間只有一條工作執行緒在跑,第一個執行完才轮到第二個,以此類推。所有請求都在單執行緒中序列化,不會阻塞應用主執行緒(UI Thread)。

換句話說,它替你省掉了兩件事:不用自己在 Service 裡手動開執行緒,也不用在任務結束時手動停掉 Service。

動手做個 Demo

下面模擬兩個耗時操作 Operation1 與 Operation2,規定 1 先跑,2 必須等 1 結束。

public class IntentServiceDemo extends IntentService {

    public IntentServiceDemo() {
        // 必須實作父類的建構子
        super("IntentServiceDemo");
    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("onBind");
        return super.onBind(intent);
    }

    @Override
    public void onCreate() {
        System.out.println("onCreate");
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        System.out.println("onStart");
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void setIntentRedelivery(boolean enabled) {
        super.setIntentRedelivery(enabled);
        System.out.println("setIntentRedelivery");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // Intent 從 Activity 傳來,靠參數區分要跑哪個任務
        String action = intent.getExtras().getString("param");
        if (action.equals("oper1")) {
            System.out.println("Operation1");
        } else if (action.equals("oper2")) {
            System.out.println("Operation2");
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        System.out.println("onDestroy");
        super.onDestroy();
    }
}

這裡刻意把生命週期方法全部印出來,方便觀察執行順序。接著在 Activity 中啟動它:

public class TestActivity extends Activity {

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

        // 可以啟動多次,每啟動一次都會派一筆工作,但 IntentService 實例只有一個
        // Operation 1
        Intent startServiceIntent = new Intent("com.test.intentservice");
        Bundle bundle = new Bundle();
        bundle.putString("param", "oper1");
        startServiceIntent.putExtras(bundle);
        startService(startServiceIntent);

        // Operation 2
        Intent startServiceIntent2 = new Intent("com.test.intentservice");
        Bundle bundle2 = new Bundle();
        bundle2.putString("param", "oper2");
        startServiceIntent2.putExtras(bundle2);
        startService(startServiceIntent2);
    }
}

最後別忘了到 AndroidManifest.xml 註冊——它畢竟還是個 Service,沒註冊完全不會作用。這個坑我當初踩過,盯著螢幕半天沒反應還找不到原因。

<service android:name=".IntentServiceDemo">
    <intent-filter>
        <action android:name="com.test.intentservice"/>
    </intent-filter>
</service>

執行結果驗證

從輸出可以清楚看到:onCreate 只被呼叫了一次,而 onStartCommand 與 onStart 各執行了兩次,對應兩筆工作。這印證了前面的說法——啟動多次,但 IntentService 的實例只有一個,這點和傳統 Service 一致。Operation1 也確實先於 Operation2 印出(中間刻意 sleep 了 2 秒),最後由 onDestroy 收尾,把 Service 銷毀。

補充一點實務上的限制:onHandleIntent() 跑在工作執行緒上,因此不能在此直接操作 UI;另外由於它是序列化處理,若某個請求特別慢,後續請求就會被拖住。若你需要的是多任務並行,IntentService 並不適合,應該改用 JobIntentService(舊版支援途徑)或 WorkManager、Coroutine 這類現代方案。

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