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

    }
}
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值