Android 10 获取已连接上的蓝牙设备的当前电量

前言

最近的项目中有获取连接蓝牙设备电量的需求,查找了一些资料,发现谷歌在Android8.0推出了一个getBatteryLevel的api,用来获取蓝牙设备电量百分比的方法,但在我的项目中android10环境,这个方法在Bluetoothdevice源码内,被标识为废弃不可直接调用的方法。如下图所示

但是研究一番发现可以通过反射,继续调用这个方法。

下面一行就是核心代码啦,level就是当前蓝牙电量的百分比

int level = (int) batteryMethod.invoke(device, (Object[]) null);//level就是当前蓝牙电量百分比

我将详细过程写入了一个工具类内,可以看到其实也非常的简单。
下面的代码仅为给各位同学提供一个思路,可以直接拿来使用,希望能帮到有需要的同学~

工具类代码

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @description: 蓝牙方法工具类
 * @author: ODM
 * @date: 2020/4/13
 */
public class BluetoothUtils {

    /**
     * 获取已连接的蓝牙设备的电量
     */
    public static void getBluetoothDeviceBattery(){
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        //获取BluetoothAdapter的Class对象
        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;
        try {
            //反射获取蓝牙连接状态的方法
            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
            //打开使用这个方法的权限
            method.setAccessible(true);
            int state = (int) method.invoke(btAdapter, (Object[]) null);

            if (state == BluetoothAdapter.STATE_CONNECTED) {
                //获取在系统蓝牙的配对列表中的设备--!已连接设备包含在其中
                Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
                for (BluetoothDevice device : devices) {
                    Method batteryMethod = BluetoothDevice.class.getDeclaredMethod("getBatteryLevel", (Class[]) null);
                    batteryMethod.setAccessible(true);
                    Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
                    isConnectedMethod.setAccessible(true);
                    boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
                    int level = (int) batteryMethod.invoke(device, (Object[]) null);
                    if (device != null && level > 0 && isConnected) {
                        String deviceName = device .getName();
                        LogUtils.d(deviceName + "    电量:  " + level);
                    }
                }
            } else {
                ToastUtils.showLong("No Connected Bluetooth Devices Found");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
原文地址:https://www.cnblogs.com/DMingO/p/12789593.html