5

I'm playing a bit with Android and writing a small app with an activity and a service. The activity starts the service on button click and it should fetch some data from a URI and return it as a result. Sometimes, data is not available or doesn't meet a criteria, and then the service should retry every X minutes even if the activity is in the background.

I've implemented the communication between the activity and the service via Intent and ResultReceiver (passed in the bundle). When implementing the service, I wanted to use the new JobScheduler component but then saw it can only accept a PersistableBundle which can't add a Parcelable object (ResultReceiver) but only the basic types.

I want the service to schedule a job that will run when network is available and every X minutes to check for data. Once it gets it, I want the data to be returned to the service so it can decide if it's acceptable or we need to retry again. If the service accepts the data, it will return it to the activity via the ResultsReceiver.

I can't use ResultsReceiver with the JobService, and it since I don't construct the JobService instance (done by the JobInfo.Builder), I can't pass it a reference to a callback object.

How can I communicate between a scheduled job and the service that invoked it?

Sorry if it's trivial, I'm not familiar with Android..

Thanks!

4

1 回答 1

6

如何在计划作业和调用它的服务之间进行通信?

一般来说,你不会。您的服务和您的活动都不可能存在。背后的要点JobScheduler是在您的应用程序不再运行时运行作业。如果您以其他方式使用它,那可能不合适。

话虽如此,欢迎您使用事件总线(greenrobot 的 EventBus 将是我的选择,尽管LocalBroadcastManager在这里也可以使用),在您的流程中引发一个事件以表明工作已完成。您的服务(或活动)可以注册总线上的事件并在引发这些事件时做出反应。然而,与此同时,如果没有注册的处理程序,事件总线完全满足于让事件“落在地板上”,因此JobService如果需要,您可以在“触发并忘记”模式下引发事件。

于 2016-05-20T14:45:47.230 回答