Android(安卓)BLE蓝牙开发中读取数据时设置Notify的方法
16lz
2021-01-26
项目又增加了一个功能,需要app能够实时监测到按钮的变化。
我就参照之前的电量获取方法,直接获取。
之前的电量获取方式
先获取服务
bluetoothGattService = bluetoothGatt.getService(UUID.fromString(SERVICE_UUID));
然后获取Characteristic
characteristic3 = bluetoothGattService.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID3));
由于在获取后不能马上读数据,所以我写了个线程,让其延迟一下再获取硬件发送的值。(这是一个大坑,一定要注意!)
new Thread(new Runnable() { @Override public void run() { try{ Thread.sleep(1500); bluetoothGatt.readCharacteristic(characteristic3); }catch (Exception e){ e.printStackTrace(); } }}).start();
但是这样之后我就发现了一个问题,如果连接上之后,只可以获取一次按钮当前的状态值。当我按下按钮的时候,蓝牙模块就会自动断开连接,然后就是各种改。但是一直都是这样的情况,怀疑是蓝牙模块的问题,就用nRF-Connect进行了测试,发现没有问题,然后也发现了再获取数据的时候需要先有一个Notification的操作。
我就去查资料,最终终于查到了关于Notification的使用方法
if(bluetoothGatt.setCharacteristicNotification(characteristic2, true)){ //获取到Notify当中的Descriptor通道 然后再进行注册 BluetoothGattDescriptor clientConfig = characteristic2 .getDescriptor(UUID.fromString(DESCRIPTOR_UUID)); clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); bluetoothGatt.writeDescriptor(clientConfig);}
这样给按钮的characteristic设置Notify后再通过bluetoothGatt.readCharacteristic()方法读取数据,就可以了。
附上参考文章链接https://www.jianshu.com/p/31db2569bf11
更多相关文章
- Android写入内部存储和sd卡
- android中获取屏幕相关信息
- 只需简单一步,android自带的示例程序 BluetoothChat 变蓝牙串口助
- Http中Cookie与Set-Cookie头
- Android网络数据xml解析
- Android(安卓)解析如何获取SDCard 内存
- Android(安卓)实现图片的自动缩放,适应分辨率不同的手机
- Android快速开发框架dyh详解(六)---工具层的使用
- Android(安卓)Sensor框架简述(一)