我们正在研究两个 Android 应用程序之间的蓝牙低功耗通信。一种是外围设备/服务器,一种是中央设备/客户端。如果数据发生变化,服务器将向客户端发送指示。然而,我们没有找到一种方法来确保数据确实在客户端得到了确认。我们如何知道客户端是否收到并确认了数据以便在服务器端做出相应的反应?
根据 Android 文档,BleutoothGattServer 有回调 onNotificationSent。 https://developer.android.com/reference/android/bluetooth/BluetoothGattServerCallback#onNotificationSent(android.bluetooth.BluetoothDevice,%20int)
然而,通过调试和做一些测试,似乎这个方法实际上只是在发送通知时被调用。无法保证该消息实际上已收到或确认。
以下是我们如何设置 GattServer 的特征
BluetoothGattService service = new BluetoothGattService(SERVICE_LOGIN_UUID,
BluetoothGattService.SERVICE_TYPE_PRIMARY);
// Write characteristic
BluetoothGattCharacteristic writeCharacteristic = new BluetoothGattCharacteristic(CHARACTERISTIC_LOGIN_UUID,
BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_READ| BluetoothGattCharacteristic.PROPERTY_INDICATE,
// Somehow this is not necessary, the client can still enable notifications
// | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ);
service.addCharacteristic(writeCharacteristic);
mGattServer.addService(service);
Run Code Online (Sandbox Code Playgroud)
然后我们通过调用此通知客户
mHandler.post(() -> {
BluetoothGattService service = mGattServer.getService(SERVICE_LOGIN_UUID);
BluetoothGattCharacteristic characteristic = service.getCharacteristic(uuid);
log("Notifying characteristic " + characteristic.getUuid().toString()
+ ", new value: " + StringUtils.byteArrayInHexFormat(value));
characteristic.setValue(value);
boolean confirm = BluetoothUtils.requiresConfirmation(characteristic); …
Run Code Online (Sandbox Code Playgroud)