服务和活动之间的数据交换
我必须在进度条上连续发布 UI 上后台服务的进度。关于如何去做的任何想法。我猜意图不会起作用,因为它们只能在活动开始后发送数据。还有其他建议吗?
更新:UI 上的进度发生在进度条上
I have to publish the progress from a background service on the UI continuously on a progress bar. Any ideas on how to go about it. Intents won't work I guess coz they can only send the data once the activity is started. Ant other suggestions?
Update : The progress on the UI happens on a progress Bar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
扩展应用程序,为整个应用程序创建一次。
当 Activity 启动时,将其引用存储到 Application 对象中的字段。 (请注意,您可以使用 Activity.getApplication 访问应用程序)。在 onPause/onResume 调用中将此字段设置为 Activity 引用或 null。
然后在Service中,您还可以通过Service.getApplication访问您的应用程序。因此,请检查您的 Activity 引用是否为非空,这意味着您的 Activity 会向用户显示,并在这种情况下根据需要通过调用 Activity 上的方法来更新 UI。
Extend Application, which is created once for entire application.
When Activity starts, store its reference to a field in your Application object. (Note that you can access Application using Activity.getApplication). Set this field to Activity reference or null in onPause/onResume calls.
Then in Service, you have also access to your Application by Service.getApplication. So look if your Activity reference is non-null, meaning that your Activity is shown to user, and update UI as needed in such case, by calling methods on your Activity.
感谢老鼠的帮助,但由于我需要根据可见的活动来更新应用程序中不同活动的进度条,我发现通过广播意图、接收器和意图过滤器更容易实现。我所要做的就是通过广播意图(应用了自定义意图过滤器)广播打包在捆绑包中的服务的进度,并在需要进度的活动中注册(在 onResume() 中)BroadcastReciever 的内部子类(具有相同的意图过滤器)。人们还可以在活动的 onPause() 方法中取消注册这些接收器,以节省内存空间。
Thanks for the help mice, but since I needed to update progress bars on different activities in my app depending on which one was visible, I found it easier to implement through Broadcast Intents and Recievers and Intent Filters. All I had to do was to Broadcast the progress in my service wrapped up in a bundle via a broadcast Intent (with a custom Intent Filter applied) and register (in onResume()) an inner subclass of BroadcastReciever in the activities which needed the progress (having the same intent filter). One can also unregister these recievers in the onPause() method of the activity to save memory headspace.