我想知道如何实现
要实现多个BLE连接,您必须存储多个
BluetoothGatt对象并将这些对象用于不同的设备。要存储多个连接对象,
BluetoothGatt可以使用
Map<>
private Map<String, BluetoothGatt> connectedDeviceMap;
在服务上
onCreate初始化
Map
connectedDeviceMap = new HashMap<String, BluetoothGatt>();
然后,在呼叫
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, intstatus)您
BluetoothGatt在参数上具有连接对象的方法也可以从中获取设备
BluetoothGatt。像
public voidonCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristiccharacteristic)您这样的其他回调方法将获得设备表单
gatt。
当您需要 writeCharacteristic 或 writeDescriptor时
,
BluetoothGatt从获取对象
Map并使用该
BluetoothGatt对象调用
gatt.writeCharacteristic(characteristic)
gatt.writeDescriptor(descriptor)不同的连接。
每个连接是否需要一个单独的线程?
我认为您不需要为每个连接使用单独的 线程 。只需
Service在后台线程上运行。
希望这对您有所帮助。



