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,一般手机厂商会进行修改,便于第三方应用读取

  <!-- This is the battery capacity in mAh (measured at nominal voltage) -->
  <item name="battery.capacity">1000</item>
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值