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

编程入门 行业动态 更新时间:2024-10-22 14:27:05

Android 10 获取已连接的<a href=https://www.elefans.com/category/jswz/34/1768306.html style=蓝牙设备的当前电量"/>

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

更多推荐

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

本文发布于:2024-03-12 03:14:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1730561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:蓝牙   电量   设备   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!