如何从后台服务更新 Android Activity 中的信息 [英] How can I update information in an Android Activity from a background Service

查看:25
本文介绍了如何从后台服务更新 Android Activity 中的信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的 Android 应用程序,它有一个 ActivityList 信息,当应用程序启动时,我计划启动一个将不断计算数据(它会发生变化)的服务,我希望 ActivityList 是与服务在应用生命周期内计算的数据同步.

I am trying to create a simple Android application that has a ActivityList of information, when the application starts, I plan to start a Service that will be constantly calculating the data (it will be changing) and I want the ActivityList to be in sync with the data that the service is calculating for the life of the app.

如何设置我的 Activity 以监听服务?这是解决此问题的最佳方法吗?

How can I set up my Activity to be listening to the Service? Is this the best way to approach this problem?

例如,如果您想象一个股票价格列表 - 数据将定期更改,并且需要与(在我的情况下)不断计算/获取数据的服务同步.

For example, if you imagine a list of stock prices - the data would be being changed regularly and need to be in sync with the (in my case) Service that is calculating/fetching the data constantly.

提前致谢

推荐答案

如何将我的活动设置为听服务?这是解决这个问题的最佳方法是什么?

How can I set up my Activity to be listening to the Service? Is this the best way to approach this problem?

在我看来,您有三个主要选择:

You have three major options, as I see it:

  1. 投票.Activity 定期向 Service 请求最新数据.恕我直言,这个选项很糟糕,但它肯定是可能的.

  1. Polling. The Activity periodically asks the Service for the latest data. IMHO, this option sucks, but it's certainly possible.

回调.根据 jax 的回答,ActivityService 注册一个回调对象(观察者").当数据发生变化时,Service 会在回调上调用一个方法,从而更新 UI.您可以看到将其与 Service 一起使用的示例 这里.

Callbacks. Per jax's answer, the Activity registers a callback object ("observer") with the Service. The Service invokes a method on the callback when the data changes, which in turn updates the UI. You can see an example of using that with a Service here.

广播Intents.Service 在数据更改时通过 sendBroadcast() 广播一个 Intent.Activity 使用 registerReceiver() 注册一个 BroadcastReceiver,并且 BroadcastReceiver 会收到传入广播的通知.这会触发 ActivityService 加载最新数据,或者可能只是从广播 Intent 中的额外数据中获取最新数据.您可以看到将这种技术与 Service 一起使用的示例 这里.

Broadcast Intents. The Service broadcasts an Intent via sendBroadcast() on a data change. The Activity registers a BroadcastReceiver using registerReceiver(), and that BroadcastReceiver is notified of an incoming broadcast. This triggers the Activity to load the latest data from the Service, or possibly just to get the latest data out of extras in the broadcast Intent. You can see an example of using that technique with a Service here.

这篇关于如何从后台服务更新 Android Activity 中的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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