Skip to content

Latest commit

 

History

History
61 lines (43 loc) · 2.79 KB

Service——向后台Service发送工作请求.md

File metadata and controls

61 lines (43 loc) · 2.79 KB

Service——向后台Service发送工作请求

原文(英文)地址

上一篇文章介绍了如何创建一个JobIntentService类.这篇文章将介绍如何通过一个Intent来触发JobIntentService去执行一个操作,这个Intent中也可以用于JobintentService执行任务(操作)的一些数据。

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

为了创建一个工作请求并将其发送给JobIntentService,我们需要创建一个IntentJobIntentService通过调用enqueueWork()将其加入工作队列。你还可以向Intent中添加一些数据以提供给JobIntentService去执行操作。您还可以选择将数据添加到Intent(以Intent extras的形式)以供JobIntentService进行任务处理。有关创建Intent的更多信息,请阅读Intent和IntentFilters——概述中的构建Intent部分。

下面的代码段演示了这个过程:

1:为名为RSSPullServiceJobIntentService类创建一个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的任何地方发送这个请求(Request)。比如,如果你需要先获取用户的输入,你可以在button点击的回调事件中发起这个请求(Request)。

当你调用了enqueueWork()之后,JobIntentService将会执行定义在它onHandleWork()方法中的任务,执行完成之后JobIntentService会自己停止自己(stop itself)。

下一步就是将任务执行的结果返回给源的Activity或者Fragment下个文档将会介绍如何使用BroadCastReceiver去实现这个目的。