如何从一个后台服务更新在Android活动信息后台、信息、Android

2023-09-12 00:59:39 作者:我满身刺你别拥

我想创建一个简单的Andr​​oid应用程序,有一个信息ActivityList,应用程序启动时,我打算启动一个服务,将不断地计算数据(它会改变),我希望ActivityList是在与数据同步服务正在计算用于该应用的寿命。

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

例如,如果你想像股价名单 - 该数据将被定期更换,并需要在与被计算/不断地获取数据的(对我来说)服务同步

在此先感谢

解决方案   我

如何建立我的活动是   听服务?难道这就是   要解决这个问题最好的方法是什么?

您有三个主要的选择,因为我看到它:

轮询。该活动定期询问服务最新的数据。恕我直言,这个选项很烂,但它肯定是可能的。

回调。每JAX的回答中,活动注册一个回调对象(观察者)与服务。该服务调用了回调的方法时数据的变化,从而更新UI。您可以看到使用的一个例子,有一个服务的。

广播意图。该服务播放器意图通过 sendBroadcast()上数据的变化。该活动注册了一个的BroadcastReceiver 使用 registerReceiver(),和该的BroadcastReceiver 通知传入的广播。这会触发活动加载从最新的数据的服务,或者可能只是为了获得最新的数据出来的群众演员在广播意图。您可以看到使用了服务的这里。

分享一个完整的社区项目 Android端加后台

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.

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.

Thanks in advance

解决方案

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:

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

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.

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.