服务和活动之间的数据交换

发布于 2024-12-07 21:42:00 字数 105 浏览 0 评论 0原文

我必须在进度条上连续发布 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

滴情不沾 2024-12-14 21:42:00

扩展应用程序,为整个应用程序创建一次。

当 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.

污味仙女 2024-12-14 21:42:00

感谢老鼠的帮助,但由于我需要根据可见的活动来更新应用程序中不同活动的进度条,我发现通过广播意图、接收器和意图过滤器更容易实现。我所要做的就是通过广播意图(应用了自定义意图过滤器)广播打包在捆绑包中的服务的进度,并在需要进度的活动中注册(在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文