バックグラウンド サービスに作業リクエストを送信する

前のレッスンでは、スペースを作成して JobIntentService クラス。この ストリーミング データで JobIntentService(次によるオペレーションの実行) Intent で作業をキューに登録しています。 この Intent でできること 必要に応じて JobIntentService を処理します。

作業リクエストを作成して JobIntentService に送信する

処理リクエストを作成して JobIntentService Intent を作成してキューに追加する を呼び出して実行します。 enqueueWork()。 必要に応じて、 JobIntentService を返します。インテントの作成について詳しくは、このモジュールのガイド インテントとインテント フィルタの [intent] セクション

次のコード スニペットは、このプロセスを示しています。

  1. 新しい Intent を <ph type="x-smartling-placeholder"></ph> JobIntentServiceRSSPullService を呼び出しました。

    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. <ph type="x-smartling-placeholder"></ph>に電話 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);
    

処理リクエストは、アクティビティまたはフラグメントのどこからでも送信できます。 たとえば、最初にユーザー入力を取得する必要がある場合は、コールバックからリクエストを送信できます。 (ボタンのクリックなどの操作に反応する)コードを作成します。

<ph type="x-smartling-placeholder"></ph>に発信した後 enqueueWork(), 「JobIntentService は、 onHandleWork() メソッドを呼び出した後、自動的に停止します。

次のステップでは、作業リクエストの結果を元のアクティビティに報告します。 追加します。次のレッスンでは、 BroadcastReceiver