how to update the battery level for every 5seconds in ble in android

前端 未结 1 1279
故里飘歌
故里飘歌 2020-12-01 23:23

in the following coding i am getting battery level of some percentage.but i want to call notify characteristics so that for every 5 to 10 secs it updates the percentage of b

相关标签:
1条回答
  • 2020-12-01 23:52

    If I well understood your question, you will need a Timer in order to check you battery level regularly.

    For instance, you could use this code after starting your device control activity, maybe at the end of the onServiceConnected method :

    please put the timer at the end of onServiceConnected() method of mServiceConnection object

    Timer timer = new Timer("batteryTimer");
    TimerTask task = new TimerTask() {
    @Override
    public void run() {
    mBluetoothLeService.getBattery();
    }
    };
    timer.scheduleAtFixedRate(task, 0, 5000);
    

    And do not forget to call timer.cancel() when the activity is finishing.

    And in the service, you could put something like that :

    public void getBattery() {
    
    if (mBluetoothGatt == null) {
    Log.e(TAG, "lost connection");
    } 
    
    BluetoothGattService batteryService = mBluetoothGatt.getService(Battery_Service_UUID);
    if(batteryService == null) {
    Log.d(TAG, "Battery service not found!");
    return;
    }
    
    BluetoothGattCharacteristic batteryLevel = batteryService.getCharacteristic(Battery_Level_UUID);
    if(batteryLevel == null) {
    Log.d(TAG, "Battery level not found!");
    return;
    }
    
    mBluetoothGatt.readCharacteristic(batteryLevel);
    }
    

    It is an example which would need to be modified but that gives you an idea on how to do it.

    Somebody already did access to the battery value in the link below : How to get the battery level after connect to the BLE device?

    0 讨论(0)
提交回复
热议问题