美文网首页
Android 获取当前电量

Android 获取当前电量

作者: 一半晴天 | 来源:发表于2018-02-27 15:03 被阅读125次

在浏览 Flutter 的示例代码中发现一一个比较好的写法。

private int getBatteryLevel() {
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
      return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    } else {
      Intent intent = new ContextWrapper(getApplicationContext()).
          registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
      return (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
          intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    }
  }

对于 Android 5.x 及以上的版本 可以通过 getIntProperty 来读取。

    /**
     * Remaining battery capacity as an integer percentage of total capacity
     * (with no fractional part).
     */
    public static final int BATTERY_PROPERTY_CAPACITY = 4;

当然这只是读取百分比的 Key。根据文档还有读取其他数据的 Key。

对于 5.x 之前的版本。主要是由于 ACTION_BATTERY_CHANGED 广播是 Stricky 广播的特性可以直接返回前一次电量变化广播的数据这一特点。因此此时 receiver 便可以为 null。

相关文章

网友评论

      本文标题:Android 获取当前电量

      本文链接:https://www.haomeiwen.com/subject/ozfmxftx.html