BATTERY_PROPERTY_CURRENT_NOW并非在每个设备上都有效。有哪些替代方案?

2022-09-04 04:58:48

我的应用使用BatteryManager.BATTERY_PROPERTY_CURRENT_NOW来获取设备的电池电流:

BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
int current = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW), context);

但是,例如,它不适用于三星Galaxy Tab A。在那里,它只返回0。

其他应用程序即使在该设备上也显示当前应用程序。他们是怎么做到的?我的方法有哪些替代方案?


答案 1

从您的问题(“仅返回0”),请查看getIntProperty上的文档:https://developer.android.com/reference/android/os/BatteryManager#getIntProperty(int)

如果该属性不受支持或存在任何其他错误,则返回

(a) 如果 targetSdkVersion < VERSION_CODES,则为 0。P

(b) Integer.MIN_VALUE如果 targetSdkVersion >= VERSION_CODES.P.


答案 2

使用此方法:

int getBatteryPercent(Context context) {
    Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    if (intent != null) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        return level * 100 / scale;
    }
    return 0;
}

推荐