I am wondering how this can be achieved
要实现多个BLE连接,您必须存储多个BluetoothGatt对象,并将这些对象用于不同的设备.要存储BluetoothGatt的多个连接对象,可以使用Map
private Map connectedDeviceMap;
On Service onCreate初始化地图
connectedDeviceMap = new HashMap();
然后在调用device.connectGatt(this,false,mGattCallbacks);之前要连接到GATT Server,请检查设备是否已连接.
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceAddress);
int connectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
if(connectionState == BluetoothProfile.STATE_DISCONNECTED ){
// connect your device
device.connectGatt(this, false, mGattCallbacks);
}else if( connectionState == BluetoothProfile.STATE_CONNECTED ){
// already connected . send Broadcast if needed
}
在BluetoothGattCallback上,如果连接状态为CONNECTED,则将BluetoothGatt对象存储在Map上;如果连接状态为DISCONNECTED,则将其从Map中删除
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
BluetoothDevice device = gatt.getDevice();
String address = device.getAddress();
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.i(TAG, "Connected to GATT server.");
if (!connectedDeviceMap.containsKey(address)) {
connectedDeviceMap.put(address, gatt);
}
// Broadcast if needed
Log.i(TAG, "Attempting to start service discovery:" +
gatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.i(TAG, "Disconnected from GATT server.");
if (connectedDeviceMap.containsKey(address)){
BluetoothGatt bluetoothGatt = connectedDeviceMap.get(address);
if( bluetoothGatt != null ){
bluetoothGatt.close();
bluetoothGatt = null;
}
connectedDeviceMap.remove(address);
}
// Broadcast if needed
}
}
同样,在onServicesDiscovered(BluetoothGatt gatt,int status)方法中,您也可以在参数上设置BluetoothGatt连接对象,然后可以从该BluetoothGatt获取设备.以及其他回调方法,例如public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic特性),您将获得gatt形式的设备.
当您需要writeCharacteristic或writeDescriptor时,请从Map中获取BluetoothGatt对象,并使用该BluetoothGatt对象为不同的连接调用gatt.writeCharacteristic(characteristic)gatt.writeDescriptor(descriptor).
Do I need a separate thread for each connection?
我认为您不需要为每个连接使用单独的线程.只需在后台线程上运行服务即可.
希望这对您有所帮助.