1

我想更准确地获取 android 电池信息。

我找到了一些给出电池电量和规模的代码,但它对我没有多大帮助。

int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

我需要更多信息。我需要具有高达 2 位小数精度的电池电量。

PS我看到路线'/sys/class/power_supply/battery/'。但我没有找到我想要的信息。

4

1 回答 1

1

试试这个它对我有用

private void getBatteryPercentage() {
    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            context.unregisterReceiver(this);
            int currentLevel = intent.getIntExtra(
                    BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            int level = -1;
            if (currentLevel >= 0 && scale > 0) {
                level = (currentLevel * 100) / scale;
            }
    Toast.makeText(getApplicationContext(), "Battery Level Remaining: " + level
                    + "%", Toast.LENGTH_LONG).show();

        }
    };
    IntentFilter batteryLevelFilter = new IntentFilter(
            Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
于 2015-01-27T07:24:14.737 回答