天天看點

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 = ;
        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");
    }
}
           

運作結果

- :: -/com.fadi.batteryanalysistool D/suhuazhi: batteryCap =  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>
           

繼續閱讀