0

This code gives me 2000 on every single device and all the previous questions of this problem on SO gives irrelevant answers.

Please somebody help

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(getContext());
    } 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(getActivity(), batteryCapacity + " mah",
                Toast.LENGTH_LONG).show();
        Log.d("Capacity",batteryCapacity+" mAh");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

But I want max capacity like CPU-Z app gives:

enter image description here

1 Answers1

0

From the documentation attached along with the source code of the PowerProfile class, the method getAveragePower() returns:

the average current in milliAmps.

Instead you have to use getBatteryCapacity() which returns

the battery capacity in mAh

And hence, you have to change the method invocation as getBatteryCapacity() takes no arguments unlike getAveragePower() which takes two arguments, so the code will be like:

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("getBatteryCapacity")
                .invoke(mPowerProfile_);
        Toast.makeText(MainActivity.this, batteryCapacity + " mah",
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        e.printStackTrace();
    } 
}
Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118