0

I have a service that opens a Bluetooth connection to a device. I need to have access to this connection from 2 activities. I know how to bind one activity to a service but what if I need to bind 2 activities to a service.

If I bind to the second activity to the service, will it create a second instance of the service?

sKhan
  • 9,694
  • 16
  • 55
  • 53

2 Answers2

3

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.

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.

You can verify all this behavior by using well-placed log statements in your code.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

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. 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

Community
  • 1
  • 1
OBX
  • 6,044
  • 7
  • 33
  • 77
  • Will the service be destroyed then a new one created? I don't want to close the connection because it takes a couple of seconds to establish a Bluetooth connection. – bumblebeetuna Feb 11 '16 at 01:07