將工作要求傳送給背景服務

上一堂課說明如何建立 JobIntentService 類別。本課程將說明如何透過 Intent 將工作加入佇列,藉此觸發 JobIntentService 執行作業。這個 Intent 您可以視需要納入 JobIntentService 處理的資料。

建立工作要求並傳送至 JobIntentService

如要建立工作要求並傳送至 JobIntentService,請建立 Intent,並呼叫 enqueueWork() 來排入執行佇列。您也可以選擇以意圖額外項目的形式,將資料新增至意圖,讓 JobIntentService 代為處理。如要進一步瞭解如何建立意圖,請參閱意圖和意圖篩選器中的「建立意圖」一節。

以下程式碼片段示範這個程序:

  1. JobIntentService 建立名為 RSSPullService 的新 Intent

    Kotlin

    /*
     * Creates a new Intent to start the RSSPullService
     * JobIntentService. Passes a URI in the
     * Intent's "data" field.
     */
    serviceIntent = Intent().apply {
        putExtra("download_url", dataUrl)
    }
    

    Java

    /*
     * Creates a new Intent to start the RSSPullService
     * JobIntentService. Passes a URI in the
     * Intent's "data" field.
     */
    serviceIntent = new Intent();
    serviceIntent.putExtra("download_url", dataUrl));
    
  2. 呼叫 enqueueWork()

    Kotlin

    private const val RSS_JOB_ID = 1000
    RSSPullService.enqueueWork(context, RSSPullService::class.java, RSS_JOB_ID, serviceIntent)
    

    Java

    // Starts the JobIntentService
    private static final int RSS_JOB_ID = 1000;
    RSSPullService.enqueueWork(getContext(), RSSPullService.class, RSS_JOB_ID, serviceIntent);
    

請注意,您可以從活動或片段中的任何位置傳送工作要求。舉例來說,如果您需要先取得使用者輸入內容,可以從會回應按鈕點選或類似手勢的回呼傳送要求。

呼叫 enqueueWork() 後, JobIntentService 會執行其 onHandleWork() 方法中定義的工作,然後停止自行停止。

下一步是將工作要求的結果回報至來源活動或片段。下一堂課將說明如何使用 BroadcastReceiver 達到此效果。