I need help. I just want to make application that reads battery capacity, like read in mAh/mA. Anyone can help me please?
I've read another thread about this, but I was confused because I need an integer from battery capacity. For example, my android has a battery with capacity 2500 mAh and I need that integer of capacity(2500) where I want to include that number in my calculation.
Thanks for the help.
This is code that I want to change, I am just confused where it must be changed.
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();
}
}
Yes, your code gives total mAh capacity. You can change that function to return the value like this:
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;
}
The getAveragePower
function returns the average current
in mA consumed by the subsystem. In this case subsystem string is battery.capacity
which returns the battery capacity.
See class code here: https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/com/android/internal/os/PowerProfile.java
And if you really want that value as int, just change it like this:
int bc = getBatteryCapacity().intValue();