很长一段时间裡,我在專案裡處理背景耗時工作一律直上 Service,完全沒注意到旁邊還躺著一個 IntentService。直到準備面試時讀到相關說明,才發現 IntentService 在許多場合比 Service 省事得多,這裡把心得整理成一篇備忘。
IntentService 是繼承自 Service 而來,所以要理解它,得先釐清 Service 的兩個常見誤解。官方文件有兩句話特別值得抄下來:
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
翻譯過來就是:
網路上不少教學直接把長時間的迴圈或網路請求寫進 Service 的 onStart(或早期的 onStartCommand)裡,而且完全不提醒這樣會引發 Application Not Responding。這是必須打掉的觀念:Service 只是一個「沒有 UI 的元件」,它的生命週期回呼依然跑在主執行緒上,耗時工作放進去一樣會卡住畫面。
所以結論很明確——如果 Service 裡確實有耗時操作,就必須自己開一條獨立執行緒去跑。那有人會問:既然都要開 Thread,為什麼不直接用 Thread 就好?兩者的差別在於 Service 具備優先級較高、能與 Activity 解耦、可被系統較晚回收等特性,適合需要延續執行的背景任務;純粹的一次性運算用 Thread 反而更輕。
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
歸納起來,IntentService 把「工作佇列處理器」這個模式所需的機械性工作全部包辦:
代價是它無法「邊跑邊更新 UI」,也不適合需要多個任務併行的場景——畢竟只有一條 worker 執行緒。若需求是並行下載或多執行緒分工,還是得回到 Service 加 ThreadPool 的路子。