In a recent project, there was a small requirement to obtain the battery power of connected bluetooth devices. I searched some information and found that Google launched a getBatteryLevel API on Android8.0 to obtain the method of obtaining the percentage of battery power of bluetooth devices. But in my project in the Android10 production environment, this method in the Bluetoothdevice class source code, has been identified as deprecated non-directly called methods. As shown in the figure below
But it turns out that you can continue to call this method through reflection.
I wrote the process into a class, without further simplification and encapsulation, the code is only to provide a way of thinking for you, I hope to help students in need, welcome to discuss ~
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.lang.reflect.Method;
import java.util.Set;
/ * * *@description: Bluetooth method utility class *@author: ODM
* @date: 2020/4/13 * /
public class BluetoothUtils {
/** * Obtain the power of the connected Bluetooth device */
public static void getBluetoothDeviceBattery(a){
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
// Get the BluetoothAdapter Class object
Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;
try {
// Reflection gets the bluetooth connection status
Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
// Open the permission to use this method
method.setAccessible(true);
int state = (int) method.invoke(btAdapter, (Object[]) null);
if (state == BluetoothAdapter.STATE_CONNECTED) {
// Get the device in the system bluetooth pairing list --! Connected devices are included
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 + "Electric quantity:"+ level); }}}else {
ToastUtils.showLong("No Connected Bluetooth Devices Found"); }}catch(Exception e) { e.printStackTrace(); }}}Copy the code