上一课向您展示了如何创建JobIntentService类。 本课程向您展示如何通过使用Intent排队工作来触发JobIntentService来运行操作。 此Intent可以选择包含要处理的JobIntentService的数据。
一、创建工作请求并将其发送到JobIntentService
要创建工作请求并将其发送到JobIntentService
,请创建一个Intent
并将其排入队列以通过调用enqueueWork()
来执行。 您可以选择将数据添加到意图(以意图附加形式)以供JobIntentService
处理。
以下代码段演示了此过程:
1、为JobIntentService创建一个名为RSSPullService的新Intent。
/*
* Creates a new Intent to start the RSSPullService
* JobIntentService. Passes a URI in the
* Intent's "data" field.
*/
mServiceIntent = new Intent();
mServiceIntent.putExtra("download_url", dataUrl));
2、调用enqueueWork()
// Starts the JobIntentService
private static final int RSS_JOB_ID = 1000;
RSSPullService.enqueueWork(getContext(), RSSPullService.class, RSS_JOB_ID, mServiceIntent);
请注意,您可以从活动或片段中的任何位置发送工作请求。 例如,如果您需要先获得用户输入,则可以从响应按钮单击或类似手势的回调发送请求。
一旦调用enqueueWork()
,JobIntentService
就会执行onHandleWork()
方法中定义的工作,然后自行停止。