如何在不同进程中的Activity和Service之间建立双向通信?
我正在努力在活动和在不同进程中运行的服务之间建立双向通信。
从Activity中查询进程没什么大不了的。但我希望进程通知活动有关事件的信息。其背后的想法是:该服务独立于实际应用程序运行。它定期查询网络服务器。如果在网络服务器上发现新任务,进程应通知该活动。
我在 AndDev.org 上找到了这个帖子,但它似乎不起作用为我。我一直在摆弄BroadcastReceiver。我已经实现了一个应该通知 Activity 的接口,但问题是侦听器始终为空,因为来自进程的广播是通过 Intent 完成的,因此扩展 BroadcastReceiver 的类将被新实例化。
如何建立双向通信?这一定是可能的。 感谢您的帮助,
工作人员
I'm working on establishing a two-way communication between an Activity and a Service which runs in a different process.
Querying the process from the Activity is no big deal. But I want the process to notify the Activity on events. The idea behind it is this: the service runs independently from the actual app. It queries a webserver periodically. If a new task is found on the webserver the process should notify the activity.
I found this thread over at AndDev.org but it doesn't seem to work for me. I've been messing around with BroadcastReceiver. I've implemented an interface which should notify the Activity but the problem is that the listener is always null since the Broadcast from the process is done via Intent, hence the class that extends BroadcastReceiver will be newly instantiated.
How can I establish a 2-way communication? This has to be possible.
Thanks for any help,
steff
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
BroadcastReceiver
或让Activity
注册回调或侦听器Service
对象 调用关键事件。上面的链接是演示这些技术的示例项目。Either use
BroadcastReceiver
or have theActivity
register a callback or listener object that theService
calls on key events. The links above are to book example projects demonstrating each of those techniques.我认为您应该让
BroadcastReceiver
使用 Intent 中的结果再次启动您的活动。或者您可以使用AIDL了解AIDL。这些示例还有一个(多个?)如何使用 AIDL 和服务的示例。但是
AIDL
对于您的目的来说可能会很麻烦。I think you should have the
BroadcastReceiver
start your activity again with the result in the Intent.Or you could use AIDL about AIDL. The samples also have an (multiple?) example how to use AIDL and services. But
AIDL
might be to much of a hassle for your purpose.您必须使用
BroadcastReceiver
来接收意图,并且当您想要通信时,只需使用适当的值创建一个意图即可。这样您应该能够在任何组件之间进行双向通信。
You have to use
BroadcastReceiver
to receive intents, and when you want to communicate simply make an Intent with appropriate values.This way you should be able to make a 2-way communication between any component.