项目又增加了一个功能,需要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

更多相关文章

  1. Android写入内部存储和sd卡
  2. android中获取屏幕相关信息
  3. 只需简单一步,android自带的示例程序 BluetoothChat 变蓝牙串口助
  4. Http中Cookie与Set-Cookie头
  5. Android网络数据xml解析
  6. Android(安卓)解析如何获取SDCard 内存
  7. Android(安卓)实现图片的自动缩放,适应分辨率不同的手机
  8. Android快速开发框架dyh详解(六)---工具层的使用
  9. Android(安卓)Sensor框架简述(一)

随机推荐

  1. 乘客的Django应用程序显示空主页
  2. 如何用所有可能的方式将一个列表分割成对
  3. 安装:Ubuntu12.04+Python3+Django1.7.9过
  4. 机器学习之路:python 文本特征提取 CountV
  5. 堆和索引堆的python实现
  6. Python Module之textwrap - 文本段落格式
  7. python正则表达式匹配时间和IP地址
  8. k近邻——kNN回归
  9. Mac中升级Python2.7到Python3.5步骤
  10. 在save方法中创建两个对象