建立背景服務

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

IntentService 具有下列限制:

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

不過,在大多數情況下,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 的程序,請參閱「傳送工作要求至背景服務」一文。