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:

  1. Polling. The Activity periodically asks the Service for the latest data. IMHO, this option sucks, but it’s certainly possible.

  2. Callbacks. Per jax’s answer, the Activity registers a callback object (“observer”) with the Service. The Service 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 a Service here.

  3. Broadcast Intents. The Service broadcasts an Intent via sendBroadcast() on a data change. The Activity registers a BroadcastReceiver using registerReceiver(), and that BroadcastReceiver is notified of an incoming broadcast. This triggers the Activity to load the latest data from the Service, or possibly just to get the latest data out of extras in the broadcast Intent. You can see an example of using that technique with a Service here.

Leave a Comment