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.