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

2018-08-15  本文已影响23人  鹿小纯0831

上一课向您展示了如何创建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()方法中定义的工作,然后自行停止。

上一篇 下一篇

猜你喜欢

热点阅读