What is the best way to implement two actions sharing one service (Bluetooth connection)?

Now the main action (Act. A) launches a Service that supports a Bluetooth connection. (He binds the service)

The service is a modified version of BluetoothChatService (Android bluetoothChat sample) ... ... modified with added Messenger and handler according to MessengerService (Android Remote Messenger Sample)

Step A ensures that Bluetooth is connected to an external device, and then starts another action (step B).

The problem is to get the service to continue to work and to properly support the Bluetooth connection to the new action. I do not know how:

  • Make sure the Service is not restarted or restored when it switches from step A to B

  • Make sure the messaging feature works as desired (from the current active action)

Do I need to reinstall the service to a new action and how can I guarantee that the BT connection will not be lost (due to another instance of the service)? Or I need to transfer the Messenger object to a new action in order to contact the service created using albed. If so, how can I do it better?

Very grateful for the answers!

+6
source share
3 answers

Make the service sticky so that it continues to work. Create a base activity class for two activities. The Activity base class can handle all the general functionality of binding to a service and provide proper communication. I would definitely recommend disabling your service when actions are paused and re-link them to actions when they resume. But this can be done once in the general activity of the base class.

Binding to a service should only start if it is not already running, and if you bind / untie in Resume / Pause, you should have only one active connection to the service at any given time.

+6
source

You either subclass Application , or store the information there (see here ), or you can make your "service" a single, so it has a static member of its type, which you initialize only if it is zero.

+1
source

This is an old question, but today I came across this situation and came up with a solution based on other answers. Since I could not find a job, I will send it to others who may be interested. I created a sticky service, and then the ServiceManager class, which is responsible for managing the life cycle and binding to the Service. Then I placed the ServiceManager class in a subclass of the Application class so that the actions can access it as global. It works well. The source is available on GitHub .

+1
source

Source: https://habr.com/ru/post/895285/


All Articles