IntentService
類別提供簡單明瞭的結構,以便在單一背景執行緒上執行作業。這可以處理長時間執行的作業,而不會影響使用者介面的回應速度。此外,IntentService
不會受到大多數使用者介面生命週期事件的影響,因此在關閉 AsyncTask
的情況下會繼續執行。
IntentService
有下列限制:
-
無法直接與使用者介面互動。如要將結果顯示在 UI 中,您必須將結果傳送至
Activity
。 -
系統會依序執行工作要求。如果某項作業在
IntentService
中執行,當您傳送其他要求時,該要求會等待第一個作業完成。 -
在
IntentService
上執行的作業無法中斷。
不過,在大多數情況下,建議您使用 IntentService
來執行簡單的背景作業。
本指南說明如何執行下列操作:
- 建立自己的
IntentService
子類別。 - 建立必要的回呼方法
onHandleIntent()
。 - 在資訊清單檔案中定義
IntentService
。
處理傳入意圖
如要為應用程式建立 IntentService
元件,請定義可擴充 IntentService
的類別,然後定義覆寫 onHandleIntent()
的方法。例如:
Kotlin
class RSSPullService : IntentService(RSSPullService::class.simpleName) override fun onHandleIntent(workIntent: Intent) { // Gets data from the incoming Intent val dataString = workIntent.dataString ... // Do work here, based on the contents of dataString ... } }
Java
public class RSSPullService extends IntentService { @Override protected void onHandleIntent(Intent workIntent) { // Gets data from the incoming Intent String dataString = workIntent.getDataString(); ... // Do work here, based on the contents of dataString ... } }
請注意,IntentService
會自動叫用一般 Service
元件的其他回呼 (例如 onStartCommand()
)。在 IntentService
中,您應該避免覆寫這些回呼。
如要進一步瞭解如何建立 IntentService
,請參閱「擴充 IntentService 類別」。
在資訊清單中定義意圖服務
IntentService
也需要在應用程式資訊清單中建立項目。提供此項目做為 <service>
元素,這是
<application>
元素的子項:
<application android:icon="@drawable/icon" android:label="@string/app_name"> ... <!-- Because android:exported is set to "false", the service is only available to this app. --> <service android:name=".RSSPullService" android:exported="false"/> ... </application>
android:name
屬性會指定 IntentService
的類別名稱。
請注意,<service>
元素不包含意圖篩選器。將工作要求傳送至服務的 Activity
會使用明確的 Intent
,因此不需要篩選條件。換句話說,只有同一個應用程式中的元件,或具有相同使用者 ID 的其他應用程式,才能存取該服務。
您現在已有基本的 IntentService
類別,可以使用 Intent
物件將工作要求傳送至該類別。請參閱「將工作要求傳送至背景服務」,瞭解建構這些物件並傳送至 IntentService
的程序。