Android BLE通讯无法发送数据,接收数据的回调重复调用

今天遇到一个问题App连接模块发送AT指令,开始可以发送数据与连接数据。断开连接之后重新连接后发送不了数据或者onCharacteristicChanged被重复调用,解决办法其实很简单。断开连接时调用gatt的close方法。如果gatt是用全局变量,需要置空。发送数据的Characteristic如果也是全局的,也需要置空。这个问题很简单,但是很容易忘,遇到之后如果没经验也不太好解决。希望可以帮到遇到此问题的人。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是在 Android 平台上使用 Bluetooth Low Energy(BLE)API 进行收发数据的示例代码: 首先,您需要在应用程序中获取 BluetoothAdapter 和 BluetoothGatt 对象。然后,您需要扫描并连接到 BLE 设备,获取其 BluetoothGatt 对象。一旦连接成功,您可以使用 BluetoothGatt 对象进行数据传输。 发送数据: ```java // 获取要发送的数据 byte[] data = "hello world".getBytes(); // 获取要发送数据的特征值对象 BluetoothGattCharacteristic characteristic = bluetoothGatt.getService(serviceUuid) .getCharacteristic(characteristicUuid); // 设置数据到特征值中 characteristic.setValue(data); // 发送数据 bluetoothGatt.writeCharacteristic(characteristic); ``` 在上面的示例代码中,`serviceUuid` 和 `characteristicUuid` 是您要发送数据的特征值的 UUID。 一旦您调用 `writeCharacteristic` 方法,BLE 设备将接收到发送的数据。如果发送成功,将会触发 `onCharacteristicWrite` 回调接收数据: 要接收 BLE 设备发送的数据,您需要在 BluetoothGatt 对象上注册接收数据回调。 ```java // 注册接收数据回调 bluetoothGatt.setCharacteristicNotification(characteristic, true); // 获取数据的描述符 BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid); // 启用数据的通知 descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); bluetoothGatt.writeDescriptor(descriptor); ``` 在上面的示例代码中,`characteristic` 是您要接收数据的特征值对象,`descriptorUuid` 是通知数据的描述符的 UUID。 一旦您调用 `setCharacteristicNotification` 和 `writeDescriptor` 方法,BLE 设备将开始将数据发送到 Android 设备。当数据到达时,将触发 `onCharacteristicChanged` 回调。在此回调中,您可以从特征值对象中获取数据并进行处理。 ```java @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { // 处理接收到的数据 byte[] data = characteristic.getValue(); // ... } ``` 请注意,BLE 通信是异步的,因此您需要在适当的回调中处理数据。如果您需要连续接收多个特征值的数据,请考虑使用 BluetoothGatt 的 `setCharacteristicNotification` 方法注册通知,以便连续接收数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值