Updating Activity UI from Intent Service?

社会主义新天地 提交于 2019-12-06 14:08:24

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/24183530/updating-activity-ui-from-intent-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!