1. 程式人生 > >Android BLE 開發讀取不到Character資料問題

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();

藍芽在建立連線後,資料傳輸需要有一定的時間間隔。如果連線之後立即讀取則會讀到空值。所以需要再連線之後間隔一定時間再進行資料的讀取。間隔時間可以自行修改。