从服务的前台活动的信息传递 [英] pass information from a service the foreground activity

查看:143
本文介绍了从服务的前台活动的信息传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在android的是不断拉传感器的信息,并通过网络接口发送它们的服务。

I have a service in android which is constantly pulling sensor information and sending them through the network interface.

在另一边,我有一个会使用这些传感器值以不同的方式几项活动。由于该服务获取一个事件驱动方式的价值观,我怎么可以通过这些值仅是在前台活动?

In the other side I have several activities that will use those sensor values in different ways. Since the service gets the values in a event driven way, how can I pass those values only to the activity that is in the foreground?

在此先感谢

推荐答案

我想这是一个本地服务的最常见的情况,也就是说,在同一个进程中运行的活动。

I'll suppose it's the most common case of a "local" service, that is, running in the same process as the activities.

有两种解决方案,一是与服务发送意图到注册和注销活动,适当的的BroadcastReceiver ONSTART()的onStop()

There are two solutions, one with the service sending intents to activities that register and deregister a proper BroadcastReceiver in onStart() and onStop().

其他作品有一个监听机制。你可以得到一个引用服务实例解释这里。写在服务使用setListener(的ServiceListener L)方法 和的ServiceListener 的界面,你就可以实现一个监听器在你的活动和服务设置。

The other works with a listener mechanism. You can get a reference to the service instance as explained here. Writing in the service a setListener(ServiceListener l) method and a ServiceListener interface you'll be able to implement a listener in your activity and set it on the service.

这样做的目的的方法可能更简单,风险较小,但你必须坚持意图演员进行数据交换。

The intent way might be simpler and less risky, but you'll have to stick to intent extras for data exchange.

监听方式更加灵活,但我读过,我们必须一定要注销的听众或你最后可能会纪念品。泄漏的整体活动。

The listener way is more flexible but I've read that one must be sure to deregister the listener or you might end up mem. leaking whole activities.

这篇关于从服务的前台活动的信息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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