我想知道如何实现这一点
要实现多个 BLE 连接,您必须存储多个 BluetoothGatt 对象并将这些对象用于不同的设备。要存储BluetoothGatt 的多个连接对象,可以使用Map<>
private Map<String, BluetoothGatt> connectedDeviceMap;
在服务onCreate初始化Map
connectedDeviceMap = new HashMap<String, BluetoothGatt>();
然后在调用device.connectGatt(this, false, mGattCallbacks); 连接到GATT 服务器之前检查设备是否已经连接。
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 中删除/p>
@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 characteristic),您将获得设备表单gatt。
当您需要writeCharacteristic 或writeDescriptor 时,从Map 获取BluetoothGatt 对象并使用该BluetoothGatt 对象调用gatt.writeCharacteristic(characteristic) gatt.writeDescriptor(descriptor)不同的连接。
每个连接都需要一个单独的线程吗?
我认为您不需要为每个连接使用单独的线程。只需在后台线程上运行Service。
希望这对您有所帮助。