Android 获取电池容量 mAh

1. Java 反射获取电池容量

目前手机出厂下配置电池容量主要是通过修改 power_profile.xml 的电池容量参数,一般Google 默认配置为 1000 mAh

故只要是出货的手机一般都需要修改该值。我们可以直接导出 frameworks\base\core\res\res\xml\power_profile.xml 进行查看与修改

或者使用 Java 反射 PowerProfile.java 求出电池容量大小,方法如下。

package com.fadi.batteryanalysistool.battery;

import android.content.Context;

/**
 * Created by fadi.su on 2018/5/22.
 */
public class BatteryInfo {

    /**
     * 获取电池容量 mAh
     *
     * 源头文件:frameworks/base/core/res\res/xml/power_profile.xml
     *
     * Java 反射文件:frameworks\base\core\java\com\android\internal\os\PowerProfile.java
     */
    public static String getBatteryCapacity(Context context) {
        Object mPowerProfile;
        double batteryCapacity = 0;
        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) {
            e.printStackTrace();
        }

        return String.valueOf(batteryCapacity + " mAh");
    }
}

运行结果

01-12 03:06:36.461 9877-9877/com.fadi.batteryanalysistool D/suhuazhi: batteryCap = 3000.0 mAh

2. Java 反射方法 getBatteryCapacity

文件路径在于:frameworks\base\core\java\com\android\internal\os\PowerProfile.java

/**
 * Reports power consumption values for various device activities. Reads values from an XML file.
 * Customize the XML file for different devices.
 * [hidden]
 */
public class PowerProfile {

    /**
     * Battery capacity in milliAmpHour (mAh).
     */
    public static final String POWER_BATTERY_CAPACITY = "battery.capacity";


    /**
     * Returns the battery capacity, if available, in milli Amp Hours. If not available,
     * it returns zero.
     * @return the battery capacity in mAh
     */
    public double getBatteryCapacity() {
        return getAveragePower(POWER_BATTERY_CAPACITY);
    }

}

3. 源文件定义

文件路径:frameworks\base\core\res\res\xml\power_profile.xml

默认情况下是 1000 mAh,一般手机厂商会进行修改,便于第三方应用读取

  
  <item name="battery.capacity">1000item>

你可能感兴趣的:(省电续航)