Android BLE 开发读取不到Character数据问题

今天在给项目添加蓝牙电量显示的功能时,用的两个Service进行蓝牙设备不同操作的,刚开始没有添加读取数据的功能,但是发现第一个Service连接并进行操作之后第二个Service不能进行正常的操作。

查了很多资料,才发现原来是两个Service之间进行切换操作需要间隔一定的时间。于是我就单独写了一个线程,让它休眠一下再进行切换。

new Thread(new Runnable() {
    @Override
    public void run() {
        try{
            Thread.sleep(100);
            //开锁控制
            bluetoothGattService = bluetoothGatt.getService(UUID.fromString(SERVICE_UUID));
            characteristic = bluetoothGattService.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID));
            //设置characteristic的通知,触发bluetoothGatt.onCharacteristicWrite()事件。
            //如果notificaiton方式对于某个Characteristic是enable的,那么当设备上的这个Characteristic改变时,
            // 手机上的onCharacteristicChanged()回调就会被促发。
            bluetoothGatt.setCharacteristicNotification(characteristic, true);
            //当所有的服务都被发现时开始传输数据
            sendOpenCode();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}).start();

然后获取硬件通过characteristic传来的电量,发现每次获取到的数据都是空的。

百度了很多,试了一下午各种各样的解决方法,结果都没有用。

后来突然灵光一现,试试让readCharacteristic()方法延迟一下,结果成功了!

//获取电池电量
bluetoothGattService2 = bluetoothGatt.getService(UUID.fromString(SERVICE_UUID2));
characteristic2 = bluetoothGattService2.getCharacteristic(UUID.fromString(CHARACTERISTIC_UUID2));
bluetoothGatt.setCharacteristicNotification(characteristic2,true);
new Thread(new Runnable() {
    @Override
    public void run() {
        try{
            Thread.sleep(500);
            bluetoothGatt.readCharacteristic(characteristic2);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}).start();

蓝牙在建立连接后,数据传输需要有一定的时间间隔。如果连接之后立即读取则会读到空值。所以需要再连接之后间隔一定时间再进行数据的读取。间隔时间可以自行修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值