Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best implement Two Activities sharing One Service (w. Bluetooth Connection)?

Right now the main Activity (Act. A) starts a Service which holds the Bluetooth Connection. (It binds the Service)

The Service is a modified version of BluetoothChatService (Android BluetoothChat Sample)... ... modified with an added Messenger and Handler in accordance with MessengerService (Android Remote Messenger Sample)

Activity A makes sure that the Bluetooth is connected to an external device, and later starts another activity (Act. B).

The problem is to get the Service to keep running and serve the Bluetooth Connection to the new activity smoothly. I don't know how to:

  • Make sure that the Service is not restarted or reinstanced, when it switches from activity A to B

  • Make sure that the messenging functionality works as desired (from the currently active activity)

Do I need to rebind the Service to the new activity, and how do I assure that the BT connection is not lost (due to other instance of Service)? Or do i need to pass along the Messenger object to the new activity to communicate with the alread instantiated Service. If so, how do I do that best?

Very thankful for answers!

like image 204
stonegoat Avatar asked Aug 17 '11 21:08

stonegoat


People also ask

What is Bluetooth API?

The app framework provides access to the Bluetooth functionality through Bluetooth APIs. These APIs let apps connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features. Using the Bluetooth APIs, an app can perform the following: Scan for other Bluetooth devices.

What is BLE in Android?

Android provides built-in platform support for Bluetooth Low Energy (BLE) in the central role and provides APIs that apps can use to discover devices, query for services, and transmit information. Common use cases include the following: Transferring small amounts of data between nearby devices.


1 Answers

Make the service "sticky" so that it will continue to run. And create a base Activity class for your 2 activities. The base Activity class can handle all the common functionality of binding with the service and providing the proper communication. I would definitely recommend unbinding your service when the activities pause and re binding them in the activities when they resume. But this can be done once in the common base class activity.

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

like image 74
Gregg Rivinius Avatar answered Nov 15 '22 10:11

Gregg Rivinius