从Intent服务更新活动UI? [英] Updating Activity UI from Intent Service?

查看:189
本文介绍了从Intent服务更新活动UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我的应用中的服务下载一些文件(10-20或取决于用户)。问题是我使用IntentSevice并发现很难更新活动UI。我知道以下更新UI的方法

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. 使用处理程序并使用Messenger将消息从服​​务发送到活动,如这个

  2. 发送广播意图。

一旦活动结束,使用第一种方法会导致问题&重新开放,我也不确定它的表现。使用秒肯定会导致性能问题,因为我需要非常频繁地更新UI(每两秒一次或两次)。有没有其他可能的方法在IntentService和Activity之间交换数据有效?或者我必须将它切换到绑定服务?

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?

推荐答案


还有其他可能的方式来交换数据在IntentService和Activity之间有效吗?

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

使用事件总线,如 LocalBroadcastManager ,greenrobot的EventBus,或Square的Otto。让 IntentService 根据需要发布事件(例如,文件下载完成时)。您的活动/片段可以在事件来自前台时注册和注销事件。如果它们位于前台,则它们将接收该事件并能够更新UI。如果需要,您甚至可以检测前台用户界面是否选择了该事件,并让服务显示通知

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.

此目录包含三个示例应用程序演示了我引用的三个事件总线实现。并且,FWIW,这里是我在最近的网络研讨会中使用事件总线的幻灯片的PDF。

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.

这篇关于从Intent服务更新活动UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆