是的,Bluetooth LE服务器可以使用Bluetooth发送通知给客户端。以下是使用Android BLE API来实现此功能的示例代码:
BluetoothGattServer gattServer = bluetoothManager.openGattServer(context, gattServerCallback); BluetoothDevice clientDevice = bluetoothAdapter.getRemoteDevice(clientAddress); gattServer.connect(clientDevice, false);
private void createGattCharacteristic() { BluetoothGattCharacteristic gattCharacteristic = new BluetoothGattCharacteristic( UUID.fromString(characteristicUuid), BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_READ, BluetoothGattCharacteristic.PERMISSION_READ); }
private void setDescriptor() { BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor( UUID.fromString(descriptorUuid), BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE); gattCharacteristic.addDescriptor(descriptor); }
private void sendNotification() { BluetoothGattCharacteristic characteristic = gattServer.getService(serviceUuid) .getCharacteristic(characteristicUuid); characteristic.setValue(value); gattServer.notifyCharacteristicChanged(clientDevice, characteristic, false); }
在此示例中,服务端创建一个GattCharacteristic并向其添加描述符,然后调用notifyCharacteristicChanged()方法将该特征值更新并通过GATT连接发送到客户端设备。
需要注意的是,通知的发送需要在经过连接后方可进行。调用connect()方法建立连接后,可以调用discoverServices()方法发现服务并且发送通知。