Ayan Roy
Ayan Roy

Reputation: 1

How to Calculate Android Device Battery Capacity?

Currently, I am working on an Android project for which I need to get the device's Battery Capacity. This function retrieves battery percentage and remaining battery current from BatteryManager and then calculates Maximum capacity (mAh). But I need to get the Battery capacity that the manufacturer claims.

Example:

My device's battery capacity is 4900 mAh (As per the manufacturer), but this function returns 4600 mAh. I need to get that 4900 mAh.

public long getBatteryCapacity(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {            
        BatteryManager mBatteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        
        Long chargeCounter = mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
        Long capacity = mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

        if (chargeCounter != null && capacity != null) {
            long value = (long) (((float) chargeCounter / (float) capacity) * 100f);
            return value;
        }
    }
    return -1;
}

Upvotes: 0

Views: 324

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93688

That's not going to work. First off, you're going to have rounding errors. None of this stuff is exact. Secondly, you're assuming that the capacity of the battery as reported by the manufacturer and the capacity of the battery Android treats as 100% are the same. They may be, but they don't have to be- Android might decide to treat 90% of battery as full, so it has the remaining 10% for emergency power/shutdown/battery maintenance (some batteries are physically harmed if actually run to 0). Or it may reserve power to account for environmental conditions (batteries work differently depending on temperature, for example). 4900 from the manufacturer is the maximum amount of charge under optimal conditions, not an actual useful number. Its only value is in direct comparison to another battery of the same technology.

Upvotes: 2

Related Questions