简体   繁体   English

具有多个侦听器的android服务

[英]android service with multiple listeners

I am having some trouble creating a NON-IPC service that allows adding/removing multiple listeners at various times, for example, I would like to be able to contact the service and "subscribe" to its events any time, or "unsubscribe" from it. 我在创建允许在不同时间添加/删除多个侦听器的NON-IPC服务时遇到了一些麻烦,例如,我希望能够随时与该服务联系并“订阅”其事件,或者从以下位置“取消订阅”它。 The service wakes up every once in a while and sends an event to all subscribed listeners. 该服务每隔一段时间唤醒一次,并将事件发送给所有订阅的侦听器。

I have been looking at stackoverflow examples, googling, etc, particularly I found something similar here: android restful api 我一直在看stackoverflow示例,谷歌搜索等,尤其是在这里我发现了类似的东西: android restful api

In that example, the suggestion is to use ResultReceiver to serve as a callback from a service. 在该示例中,建议使用ResultReceiver充当服务的回调。 But in this approach, doesn't it mean that the service can only notify listeners sent to it as part of the first intent (ie I cannot add/remove listeners whenever I want)? 但是用这种方法,这是否意味着服务只能通知作为第一个意图的一部分发送给它的侦听器(即,我无法随时添加/删除侦听器)?

Also, in that example, what happens if the activity gets destroyed by the OS for some reason, but the service still has a reference to the listener and tries to invoke it? 另外,在该示例中,如果活动由于某种原因被OS破坏,但是该服务仍具有对侦听器的引用并尝试调用它,将会发生什么? The listener will try to perform some action on the activity, which no longer exists, right? 侦听器将尝试对不再存在的活动执行某些操作,对吗?

Maybe I am missing something... I'd appreciate some input if possible.. 也许我缺少了一些东西……如果可能的话,我将不胜感激。

Tnx 特纳克斯

First, 'sleeping' services are anti-pattern in Android. 首先,“睡眠”服务是Android中的反模式。 If you need to do something periodically, start your service using AlarmManager. 如果需要定期执行某些操作,请使用AlarmManager启动服务。 Second, the service can be restarted at any time, so you cannot rely on 'subscribing' where you keep references to other components (activities mostly). 其次,该服务可以随时重新启动,因此您不能依靠“订阅”保留对其他组件(主要是活动)的引用。 If you need to send a notification to multiple activities, use a broadcast receiver. 如果您需要向多个活动发送通知,请使用广播接收器。 Activities can register for it statically (using AndroidManifest.xml), or dynamically (with code). 活动可以静态(使用AndroidManifest.xml)或动态(使用代码)进行注册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM