Pass context to JobService Android JobScheduler

2019-07-11 16:41发布

问题:

I am building an app where I store the url and Json in my local SQLite db and then schedule a JobService.

In the JobService, I take out all the requests one by one from the db and execute them. Once they are executed, I get the response inside the JobService only. Now my real problem is how do I send the response back to the user from the service.

I thought of implementing a callback/listener in activity and passing the value in listener object inside the service. But I am taking out the requests from the SQLite db. So I don't know how to save the callback instance or the context inside my database so that I get that with the rest of the data inside the service itself.

Any ideas?

回答1:

One approach is to use an event bus implementation: LocalBroadcastManager, greenrobot's EventBus, some Rx-based bus, or even a simple MutableLiveData singleton. Have the service post a message on the bus. Have your UI layer register and unregister from the bus as they come and go. Have the UI layer process messages received on the bus, and have the service raise a Notification if the UI layer does not pick up the message.

Here are sample implementations using:

  • LocalBroadcastManager: https://github.com/commonsguy/cw-omnibus/tree/v8.6/EventBus/LocalBroadcastManager
  • greenrobot's EventBus: https://github.com/commonsguy/cw-omnibus/tree/v8.6/EventBus/GreenRobot3
  • MutableLiveData: https://github.com/commonsguy/cw-androidarch/tree/v0.1/General/LiveBus