'Android BLE multiple connections

I am trying to create an application that connects and receives notifications from multiple bluetooth low energy devices. I am wondering how this can be achieved. Do I need a separate thread for each connection? How can I make sure the services get discovered and notifications get set in an order that works given the asynchronous nature of the API. I am currently using the same structure provided here: https://developer.android.com/guide/topics/connectivity/bluetooth-le.html. This is setup for a single connection only. Would I be able to keep this structure i.e. extending the Service class in the BluetoothLeService class and binding to the service. I have recently discovered that The Service class is a singleton so how would I go about creating different instances of my BluetootLeService class and receiving broadcast and registering the Broadcast Receiver/Receivers to handle changes from the appropriate devices.



Solution 1:[1]

Abu Yousuf's answer really helped me, also because I couldn't find anything similiar on the Internet. I'd like to add one thing I struggled with: Better not save your BluetoothGattCharacteristic in a global variable because it is unique and different for every connected device. So rather retrieve it in every action, e.g. when you want to write a new value:

BluetoothGatt gatt = connectedDeviceMap.get(address);
BluetoothGattCharacteristic localChar = gatt.getService(SERVICE_UUID).getCharacteristic(CHAR_UUID);
localChar.setValue(value);
gatt.writeCharacteristic(localChar);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris