ashu
ashu

Reputation: 1826

Updating Activity UI from Intent Service?

I need to download some files (10-20 or depends on user) from service in my app. The problem is I am using IntentSevice and finding it hard to update activity UI. I know following ways to update UI

  1. Use handler and send messages from service to activity using Messenger like this.
  2. Send broadcast intents.

Using first method would cause problem once activity is closed & re-opened and also I am not sure about its performance. Using second would definitely cause perfomance issues since I need to update UI quite frequently (once or twice every two seconds). Is there anyother possible way of exchanging data between IntentService and Activity which is efficient? or I have to switch it to Bound Service?

Upvotes: 1

Views: 3642

Answers (2)

brummfondel
brummfondel

Reputation: 1210

Try LocalBroadcastManager (http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html). Faster than Broadcast Service.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006614

Is there anyother possible way of exchanging data between IntentService and Activity which is efficient?

Use an event bus, like LocalBroadcastManager, greenrobot's EventBus, or Square's Otto. Have the IntentService post events as needed (e.g., when a file is done downloading). Your activities/fragments can register and unregister for events as they come and go from the foreground. If they are in the foreground, they will receive the event and be able to update the UI. You can even detect if the event was not picked up by the foreground UI and have the service display a Notification, if desired.

This directory contains three sample apps demonstrating this for the three event bus implementations that I cited. And, FWIW, here is the PDF of slides that I used in recent webinars on using event buses.

Upvotes: 3

Related Questions