上一课介绍了如何创建 JobIntentService
类。本节课介绍如何通过 Intent
将工作加入队列,以触发 JobIntentService
来运行某项操作。此 Intent
可以选择性地包含要供 JobIntentService
处理的数据。
创建工作请求并将其发送到 JobIntentService
如需创建工作请求并将其发送到 JobIntentService
,请创建一个 Intent
并将其加入队列,以便通过调用 enqueueWork()
执行。您可以选择性地将数据添加到 intent(以 intent extra 形式)以供 JobIntentService 处理。如需详细了解如何创建 intent,请参阅 intent 和 intent 过滤器中的“构建 intent”部分
以下代码段演示了此过程:
-
为名为
RSSPullService
的JobIntentService
新建Intent
。
/*
* 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)
}/*
* 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()
private const val RSS_JOB_ID = 1000
RSSPullService.enqueueWork(context, RSSPullService::class.java, RSS_JOB_ID, serviceIntent)// Starts the JobIntentService
private static final int RSS_JOB_ID = 1000;
RSSPullService.enqueueWork(getContext(), RSSPullService.class, RSS_JOB_ID, serviceIntent);
请注意,您可以从 activity 或 fragment 中的任意位置发送工作请求。例如,如果您需要先获得用户输入,则可从响应按钮点击或类似手势的回调发送请求。
调用
enqueueWork()
后,
JobIntentService
会执行其
onHandleWork()
方法中定义的工作,然后自行停止。
下一步是将工作请求的结果返回给源 Activity 或 Fragment。下节课将介绍如何使用 BroadcastReceiver
执行此操作。