简体   繁体   English

如何将多个活动绑定到服务

[英]How to bind multiple activities to a service

I have a service that opens a Bluetooth connection to a device. 我有一项服务可打开与设备的蓝牙连接。 I need to have access to this connection from 2 activities. 我需要从2个活动中访问此连接。 I know how to bind one activity to a service but what if I need to bind 2 activities to a service. 我知道如何将一个活动绑定到服务,但是如果我需要将2个活动绑定到服务怎么办。

If I bind to the second activity to the service, will it create a second instance of the service? 如果将第二个活动绑定到服务,它将创建服务的第二个实例吗?

The other answer is not really correct (I don't think they read their own doc references). 另一个答案不是真的正确(我不认为他们阅读了自己的文档参考)。 You can bind multiple times to a service without any problems. 您可以多次绑定到服务,而不会出现任何问题。 Each connection to the service will operate independently of each other, and their ServiceConnection objects will reflect when they independently connect and disconnect. 与服务的每个连接都将彼此独立运行,并且它们的ServiceConnection对象将反映它们何时独立连接和断开连接。

There will only ever be one instance of a service as defined in the manifest. 清单中定义的服务将永远只有一个实例 When a client is bound for the first time, the service object will be created. 第一次绑定客户端时,将创建服务对象。 Each new client will not create a new object instance of that service. 每个新客户端都不会创建该服务的新对象实例。 But when the last client is unbound, the service destroy (as long as it is not also currently "started") by onStartCommand. 但是,当最后一个客户端解除绑定时,服务将被onStartCommand销毁(只要它当前还没有“启动”即可)。

You can verify all this behavior by using well-placed log statements in your code. 您可以通过在代码中使用放置适当的日志语句来验证所有这些行为。

will it create a second instance of the service? 它将创建服务的第二个实例吗?

Yes, it does 是的,它确实

However, multiple instance of the same service cannot be run simultaneously! 但是,同一服务的多个实例不能同时运行!

Possible solution to your problem would be :to bind the Service in the onResume() method, and unbind it in the onPause() method. 解决您的问题的可能方法是:将Service绑定到onResume()方法中,并将其取消绑定到onPause()方法中。 This allows you to give two un-related Activities access to the service, while only having one bound at a time. 这使您可以为两个不相关的活动授予对该服务的访问权限,而一次只能绑定一个。

For further info, read these questions as well: 有关更多信息,请阅读以下问题:

Also, consider reading this article on local bound services 另外,请考虑阅读有关本地绑定服务的本文

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

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