How can I update information in an Android Activity from a background Service
How can I set up my Activity to be listening to the Service? Is this the best way to approach this problem?
You have three major options, as I see it:
Polling. The
Activity
periodically asks theService
for the latest data. IMHO, this option sucks, but it's certainly possible.Callbacks. Per jax's answer, the
Activity
registers a callback object ("observer") with theService
. TheService
invokes a method on the callback when the data changes, which in turn updates the UI. You can see an example of using that with aService
here.Broadcast
Intents
. TheService
broadcasts anIntent
viasendBroadcast()
on a data change. TheActivity
registers aBroadcastReceiver
usingregisterReceiver()
, and thatBroadcastReceiver
is notified of an incoming broadcast. This triggers theActivity
to load the latest data from theService
, or possibly just to get the latest data out of extras in the broadcastIntent
. You can see an example of using that technique with aService
here.
This sound like a good candidate for the Observer Pattern. Basically your activity (The Observer) will register itself with the background service (The Observable) and you can push or pull data from your Activity. Your Observer in this case will be your Activity and the Observable will be your Service.
If you know nothing about Design Patterns buy "Head First Design Patterns", it is easy to read and is full of great information.
PS: I am reading it now.
I am really, really wondering why no one mentioned a simple approach using an EventBus by whatever library. This is of course if you are not using RX. My personal favorite is EventBus by GreenRobot.https://github.com/greenrobot/EventBus
With just a couple of lines of code, and no interfaces. Fire an event, and listen for it wherever you want. It is decoupled, it is thread safe, and it will not crash your app.