前のレッスンでは、JobIntentService
クラスを作成する方法について説明しました。このレッスンでは、Intent
で処理をキューに登録して、JobIntentService
をトリガーしてオペレーションを実行する方法について説明します。
この Intent
には、JobIntentService
が処理するデータを含めることもできます。
作業リクエストを作成して JobIntentService に送信する
処理リクエストを作成して JobIntentService
に送信するには、Intent
を作成し、
enqueueWork()
を呼び出して実行されるようにキューに登録します。
必要に応じて、JobIntentService が処理するデータを(インテント エクストラの形式で)インテントに追加できます。インテントの作成の詳細については、インテントとインテント フィルタの「インテントの作成」セクションをご覧ください。
次のコード スニペットは、このプロセスを示しています。
-
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));
-
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);
WorkRequest は、アクティビティやフラグメントのどこからでも送信できます。たとえば、最初にユーザー入力を取得する必要がある場合は、ボタンのクリックや同様の操作に応答するコールバックからリクエストを送信できます。
enqueueWork()
を呼び出すと、
JobIntentService
は
onHandleWork()
メソッドで定義された処理を実行して、自己停止します。
次のステップでは、処理リクエストの結果を元のアクティビティまたはフラグメントに報告します。次のレッスンでは、BroadcastReceiver
を使用してこれを行う方法について説明します。