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

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