将工作请求发送到后台服务

上一课展示了如何创建 JobIntentService 类。本课介绍了如何通过使用 Intent 将工作加入队列来触发 JobIntentService 来运行某项操作。此 Intent 可以选择包含要供 JobIntentService 处理的数据。

创建工作请求并将其发送到 JobIntentService

如需创建工作请求并将其发送到 JobIntentService,请创建一个 Intent 并通过调用 enqueueWork() 将其加入队列以便执行。您还可以选择向 intent 添加数据(以 intent extra 的形式)供 JobIntentService 处理。如需详细了解如何创建 intent,请参阅 intent 和 intent 过滤器中的“构建 intent”部分

以下代码段演示了此过程:

  1. 为名为 RSSPullService JobIntentService 新建 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));
    
  2. 调用 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 执行此操作。