Steve Brooker
Steve Brooker

Reputation: 1183

How to pass data from an Android background service to an activity

I have an Android app, with two components

  1. An activity which creates, displays and communicates with javascript code running in a webview.
  2. A background service which is created and bound to the above activity, which captures location data, even when the activity is not visible to the user.

Please can someone tell me the simplest way to pass the location data from the service back to the activity that will work whether or not the activity is displayed to the user.

Should I use EventBus? Broadcast Receiver, Local Broadcast Manager or what?

Ideally I would like to be pointed in the direction of an example app on GitHub (or similar) that I can download an examine how it works, failing that some code would be nice.

Upvotes: 1

Views: 1488

Answers (2)

Steve Brooker
Steve Brooker

Reputation: 1183

I found the easiest solution was in fact using EventBus. Their website getting started page states four simple steps

  1. In my gradle file add "implementation 'org.greenrobot:eventbus:3.1.1'"
  2. In my MainActivity register and unregister the receiver. I did this in onCreate and onDestroy, but they recommend onStart and onStop
  3. Add a new JavaClass MessageEvent - 4 lines of code from link above
  4. In my service use EventBus to post new location data when available
  5. In my MainActivity react to these posts with onMessageEvent

this works well even when the main activity is paused (in the background)

Two little extras things to do, that were not documented in the link above.

  1. I had to add "import org.greenrobot.eventbus.EventBus;" to both my MainActivity class file and to my BackgroundService class file.
  2. have to add mavenCentral() to the all projects section of the top level build file.

Upvotes: 1

zeekhuge
zeekhuge

Reputation: 1594

Since you are using a Bound service, the simplest way would be to return an appropriate Binder object when the Activity binds to the Service.

The documentation for that is in here.

Also, this is the sample code for a bound service and the corresponding actvitiy.

Note that the Activity, once connected, is able to call the public methods that were added to the corresponding Binder objects. If you want the Service to provide info to the Activity at its own discretion, simply register a listener that the service could invoke.

Upvotes: 0

Related Questions