首页 > 解决方案 > 从蓝牙 A2DP 设备 Android 读取电池电量

问题描述

我正在尝试读取我的蓝牙耳机(Skullcandy Method Wireless)的电池电量。到目前为止,我在连接耳机时成功接收连接广播,通过 bluetoothDevice.connectGatt() 连接到 GATT。

//getting device
  BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

在 BluetoothGattCallback.onConnectionChanged 上,我正在调用 discoverServices() 来发现蓝牙 Battery_Service。但服务列表始终为零。

BluetoothGatt bluetoothGatt = device.connectGatt(context, false, new BluetoothGattCallback() {

            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                super.onConnectionStateChange(gatt, status, newState);
                Logger.log(A2dpConnectionStateReceiver.class, "onConnectionStateChange "+newState);
                if(newState == BluetoothProfile.STATE_CONNECTED) {
                    Logger.log(A2dpConnectionStateReceiver.class, "onConnectionStateChange state connected, triggering discover services " + gatt.discoverServices());
                }
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                super.onServicesDiscovered(gatt, status);
                Logger.log(A2dpConnectionStateReceiver.class, "onServicesDiscovered count = "+gatt.getServices().size()+" status="+ (status == BluetoothGatt.GATT_SUCCESS? "success" : "failed") );

            }

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                super.onCharacteristicChanged(gatt, characteristic);
                Logger.log(A2dpConnectionStateReceiver.class, "onCharacteristicChanged "+characteristic.getUuid());
                if(characteristic.getUuid().equals(Battery_Level_UUID)) {
                    Logger.log(A2dpConnectionStateReceiver.class, "onCharacteristicChanged battery level at "+characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));
                }
            }
        });

标签: androidbluetoothheadphones

解决方案


推荐阅读