建立背景服務

IntentService 類別提供簡單的結構,可在單一背景執行緒上執行作業。以便處理長時間執行的作業,而不會影響使用者介面的回應速度。此外,大部分的使用者介面生命週期事件都不會影響 IntentService,因此在關閉 AsyncTask 的情況下會繼續執行

IntentService 有幾項限制:

  • 無法直接與使用者介面互動,如要將結果放入 UI,您必須將結果傳送至 Activity
  • 工作要求會依序執行。如果作業是在 IntentService 中執行,當您傳送其他要求時,該要求會等到第一個作業完成為止。
  • IntentService 上執行的作業無法中斷。

不過在大多數情況下,建議您使用 IntentService 執行簡易背景作業。

本指南將說明如何執行下列操作:

處理傳入的意圖

如要為應用程式建立 IntentService 元件,請定義可擴充 IntentService 的類別,並在其中定義覆寫 onHandleIntent() 的方法。例如:

KotlinJava
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
       
...
   
}
}
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
       
...
   
}
}

請注意,Service 元件的其他回呼 (例如 onStartCommand()) 會由 IntentService 自動叫用。在 IntentService 中,請避免覆寫這些回呼。

如要進一步瞭解如何建立 IntentService,請參閱「擴充 IntentService 類別」。

在資訊清單中定義意圖服務

IntentService 也需要應用程式資訊清單中的項目。將這個項目做為 <application> 元素的子項 <service> 元素提供:

    <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,請參閱「將工作要求傳送至背景服務」一文。