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

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

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

我将过程写入了一个类内,没有进一步简化和封装

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

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章