上一课介绍了如何创建
JobIntentService 类。本次
如何触发
JobIntentService,用于执行以下操作:
使用 Intent 将工作加入队列。
此Intent可以
(可选)包含
JobIntentService 进行处理。
创建工作请求并将其发送到 JobIntentService
要创建工作请求并将其发送到
JobIntentService、
创建 Intent 并将其加入队列,
调用
enqueueWork()。
您可以选择向 intent 添加数据(以 intent extra 的形式)
JobIntentService 进行处理。如需详细了解如何创建 intent,请参阅“构建
intent 部分(intent 和 intent 过滤器)
以下代码段展示了此过程:
-
创建一个新的
Intent,用于JobIntentService已调用RSSPullService。
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);
请注意,您可以从 activity 或 fragment 中的任意位置发送工作请求。 例如,如果您需要首先获取用户输入,可以通过回调发送请求 响应按钮点击或类似手势。
调用 后,
enqueueWork(),
JobIntentService 会执行其
onHandleWork() 方法,然后自行停止运行。
下一步是将工作请求的结果报告回源 activity
或 Fragment。下一课将介绍如何使用
BroadcastReceiver。