查询电池容量

时间:2014-03-09 17:03:29

标签: android battery

我需要帮助。我只想制作读取电池容量的应用程序,例如以mAh / mA读取。有人可以帮我吗?

我已经阅读了另一个关于此问题的帖子,但我很困惑,因为我需要一个来自电池容量的整数。例如,我的android有一个容量为2500 mAh的电池 我需要容量的整数(2500),我想在计算中包含该数字。

感谢您的帮助。

这是我想要改变的代码,我只是在必须改变的地方感到困惑。

public void getBatteryCapacity() {
        Object mPowerProfile_ = null;

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

        try {
            mPowerProfile_ = Class.forName(POWER_PROFILE_CLASS)
                    .getConstructor(Context.class).newInstance(this);
        } catch (Exception e) {
            e.printStackTrace();
        } 

        try {
            double batteryCapacity = (Double) Class
                    .forName(POWER_PROFILE_CLASS)
                    .getMethod("getAveragePower", java.lang.String.class)
                    .invoke(mPowerProfile_, "battery.capacity");
            Toast.makeText(MainActivity.this, batteryCapacity + " mah",
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

1 个答案:

答案 0 :(得分:2)

是的,您的代码可提供总mAh容量。您可以更改该函数以返回如下值:

public Double getBatteryCapacity() {

  // Power profile class instance
  Object mPowerProfile_ = null;

  // Reset variable for battery capacity
  double batteryCapacity = 0;

  // Power profile class name 
  final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";

  try {

    // Get power profile class and create instance. We have to do this 
    // dynamically because android.internal package is not part of public API
    mPowerProfile_ = Class.forName(POWER_PROFILE_CLASS)
                    .getConstructor(Context.class).newInstance(this);

  } catch (Exception e) {

    // Class not found?
    e.printStackTrace();
  } 

  try {

    // Invoke PowerProfile method "getAveragePower" with param "battery.capacity"
    batteryCapacity = (Double) Class
                    .forName(POWER_PROFILE_CLASS)
                    .getMethod("getAveragePower", java.lang.String.class)
                    .invoke(mPowerProfile_, "battery.capacity");

  } catch (Exception e) {

    // Something went wrong
    e.printStackTrace();
  } 

    return batteryCapacity;
 }

getAveragePower函数返回平均电流 以子系统消耗的mA。在这种情况下,子系统字符串是battery.capacity,它返回电池容量。

请在此处查看课程代码: https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/com/android/internal/os/PowerProfile.java

如果你真的希望这个值为int,那就改变它:

int bc = getBatteryCapacity().intValue();