今天在给项目添加蓝牙电量显示的功能时,用的两个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();
蓝牙在建立连接后,数据传输需要有一定的时间间隔。如果连接之后立即读取则会读到空值。所以需要再连接之后间隔一定时间再进行数据的读取。间隔时间可以自行修改。