当前位置: 移动技术网 > IT编程>移动开发>Android > Android Ble notify功能踩坑(解决)

Android Ble notify功能踩坑(解决)

2018年02月14日  | 移动技术网IT编程  | 我要评论

中国忠旺控股,鬼道猎魂,国王的演讲 台词

最近在研究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上一个开源的框架。通过进入内部源码查看才知道,如果获取不到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,这个需要后面继续了解,先记录下自己踩过的坑,让别人少踩坑。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网