前言
最近的項目中有獲取連接藍牙設備電量的需求,查找了一些資料,發現谷歌在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();
}
}
}