Android获取电池电量和电池容量

2019-07-11  本文已影响0人  new和光同尘

测试APK,获取电量信息,做一些耗电相关的测试,必须要用到一段时间内的耗电百分比,和当前手机的电池容量,计算出平均的耗电电流

1. 获取电池电量百分比

    可以使用BatteryManager,废话不多说上代码:

    BatteryManager manager = (BatteryManager)context.getSystemService(context.BATTERY_SERVICE);

    int currentLevel = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

2. 获取电池容量

    查了好久,没有找到直接获取的方式,获取电池容量可以通过java反射 PowerProfile类获取(PowerProfile.java,实际是读取power_profile.xml读取,xml中保存了当前机型的场景下的耗电系数或这一些固定的值  比如: 每个CPU频点的耗电系数  子系统的耗电系数、总电量等信息)

Object mPowerProfile;

double batteryCapacity =0; //电池的容量mAh

final String POWER_PROFILE_CLASS ="com.android.internal.os.PowerProfile";

try {

mPowerProfile = Class.forName(POWER_PROFILE_CLASS).getConstructor(Context.class).newInstance(context);

    batteryCapacity = (double) Class.forName(POWER_PROFILE_CLASS).getMethod("getBatteryCapacity").invoke(mPowerProfile);

}catch (Exception e) {

printLog("get batteryCapacity mAh error: " + batteryCapacity);

    e.printStackTrace();

}

引申:

获取power_profile.xml文件,

1. 没有办法直接获取

2. 通过拿到手机中framework-res.apk(APK路径 /system/framework/)然后反编译APK

3.反编译后存在于res/xml/power_profile.xml(Android工程中存放的路径)

4. 反编译APK 参考:https://www.jianshu.com/p/dba82e730cf7

对应的power_profile.xml

  <item name="battery.capacity">3120</item>  整个是电池容量

<array name="cpu.core_speeds.cluster0">  CPU 小核的所有频点

      <value>300000</value>

      <value>576000</value>

      <value>748000</value>

      <value>998400</value>

      <value>1209600</value>

      <value>1324800</value>

      <value>1516800</value>

      <value>1612800</value>

      <value>1780000</value>

  </array>

  <array name="cpu.core_power.cluster0">  CPU小核对应每个频点满负荷的功耗

      <value>31.84</value>

      <value>35.91</value>

      <value>37.69</value>

      <value>45.77</value>

      <value>53.89</value>

      <value>59.62</value>

      <value>66.80</value>

      <value>72.52</value>

      <value>80.99</value>

  </array>

系统常用的一些场景的耗电量,列出来几个

<item name="screen.on">64.19</item>

  <item name="bluetooth.active">9.22</item>

  <item name="gps.on">132.43</item> <!-- ~50mA -->

上一篇 下一篇

猜你喜欢

热点阅读