Total Battery Capacity in mAh of device Programmatically

℡╲_俬逩灬. 提交于 2019-12-04 05:15:46

For those users interested in the implementation of the @Yehan suggestions, here is a method that return the total battery capacity: (only for API Level >= 21)

public long getBatteryCapacity(Context context) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        BatteryManager mBatteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        Integer chargeCounter = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
        Integer capacity = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

        if(chargeCounter == Integer.MIN_VALUE || capacity == Integer.MIN_VALUE)
            return 0;

        return (chargeCounter/capacity) *100;
    }
    return 0;
}

Unfortunately, for some reason this approach doesn't always work. In those cases, you can use Java's Reflection APIs to retreive the value returned by getBatteryCapacity method of com.android.internal.os.PowerProfile :

public double 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 batteryCapacity;

}

Source: https://android.googlesource.com/platform/frameworks/base/+/a029ea1/core/java/com/android/internal/os/PowerProfile.java

You can use following properties of android.os.BatteryManager. BATTERY_PROPERTY_CHARGE_COUNTER which gives you the remaining battery capacity in microampere-hours. BATTERY_PROPERTY_CAPACITY which gives you the remaining battery capacity as an integer percentage.

So,

BATTERY_PROPERTY_CHARGE_COUNTER / BATTERY_PROPERTY_CAPACITY * 100

would give you the Total Battery Capacity. This would not be the precise calculation but you will be able to close the actual capacity.

References: https://source.android.com/devices/tech/power/index.html#device-power http://developer.android.com/reference/android/os/BatteryManager.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!