android ble notify,Android Ble notify功能踩坑

最近在研究Ble蓝牙相关的开发,在和蓝牙通信的时候,主动读取消息是ok的,但是就是无法收到蓝牙主动发送出来的消息,而且IOS是可以接收到消息的。这个就比较尴尬了。

通过查阅文档和网上他人的博客找到开启notify功能的代码:

private void setAutoReceiveData(BluetoothGatt gatt) {

try {

BluetoothGattService linkLossService = gatt.getService(SERVICE_UUID);

BluetoothGattCharacteristic data = linkLossService.getCharacteristic(CHARACTERISTIC_UUID);

BluetoothGattDescriptor descriptor = data.getDescriptor(CHARACTERISTIC_UUID);

if (null != descriptor) {

descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

bluetoothGatt.writeDescriptor(descriptor);

}

bluetoothGatt.setCharacteristicNotification(data, true);

} catch (Exception e) {

BleLogUtils.appendLog("setAutoReceiveData:" + e.getMessage());

}

}

通过serviceId获取到对应的service,并从service中获取到对应的BluetoothGattCharacteristic信息。根据BluetoothGattCharacteristic获取到对应的BluetoothGattDescriptor,但是这里每次获取都是为空的,所以无法进行设置,这样的话Android是无法收到蓝牙发送的消息的。

于是对比目前应用市场上的Ble开发工具,通过其他工具是可以正常接收到蓝牙发送的消息的。

基本上定位到是自己程序的问题后,就开始进行问题调查,知道查到github上一个开源的框架:https://github.com/xiaoyaoyou1212/BLE 通过进入内部源码查看才知道,如果获取不到BluetoothGattDescriptor的时候, 这时候可以通过获取系统默认的BluetoothGattDescriptor,进行蓝牙接口设置。修改后的代码如下:

public static final String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";

private void setAutoReceiveData(BluetoothGatt gatt) {

try {

BluetoothGattService linkLossService = gatt.getService(SERVICE_UUID);

BluetoothGattCharacteristic data = linkLossService.getCharacteristic(CHARACTERISTIC_UUID);

BluetoothGattDescriptor defaultDescriptor = data.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG));

if (null != defaultDescriptor) {

defaultDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

bluetoothGatt.writeDescriptor(defaultDescriptor);

}

bluetoothGatt.setCharacteristicNotification(data, true);

} catch (Exception e) {

BleLogUtils.appendLog("setAutoReceiveData:" + e.getMessage());

}

}

问题完美解决,这个还是主要对BLE不熟悉导致的。为什么可以从CLIENT_CHARACTERISTIC_CONFIG 中获取到BluetoothGattDescriptor,这个需要后面继续了解,先记录下自己踩过的坑,让别人少踩坑。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值