How to get the battery level after connect to the BLE device?

前端 未结 1 1475
春和景丽
春和景丽 2020-12-01 03:28

I am developing an application where I have to connect to Bluetooth device on Android 4.3.

And I want to get the battery level by using Battery_Service

相关标签:
1条回答
  • 2020-12-01 03:48

    I have solved this problem.

    public class BluetoothLeService extends Service {
    
        private static final UUID Battery_Service_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb");
        private static final UUID Battery_Level_UUID = UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb");
    
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    
            if(status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }
    
    
        private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    
            final Intent intent = new Intent(action);   
            Log.v(TAG, "characteristic.getStringValue(0) = " + characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));
            intent.putExtra(DeviceControl.EXTRAS_DEVICE_BATTERY, characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));  
            sendBroadcast(intent);
        }
    
        public void getbattery() {
    
            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);
            Log.v(TAG, "batteryLevel = " + mBluetoothGatt.readCharacteristic(batteryLevel));
        }
    }
    

    When you call the function getbattery() , it will call onCharacteristicRead. and onCharacteristicRead will call broadcastUpdate and transmit the characteristic and action to it.

    And the characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0) in broadcastUpdate is the battery value of the BLE device.

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