'BatteryManager's BATTERY_PROPERTY_CURRENT_NOW returning 0 or incorrect current value

I am using using BattteryManager on android to get the discharging/charging current on my app. But I've notice that although it works on many devices, but in some devices like Samsung (android 10), Realme (android 10) and Huawei (android 9) the code mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) returns 0 or 1/2 (which is definitely an incorrect value). Why is this happening and is there any workaround for this?



Solution 1:[1]

I think Samsung or some devices return value in milli-ampere(mA) while other devices return value in micro-ampere(uA) as per android documentation so if you divide that value it return very small float and in integer it returns 0 so you have to check wheter your value is divisble by 1000 or not

public static Double getBatteryCurrentNow(final Context context) {
    int value = 0;

    BatteryManager manager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
    if (manager != null) {
        value = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
    }

    double curr = value;
   // curr = abs(value/1000);

    Log.d("aTag", "getBatteryCurrentNow 1: "+  curr);
     if(abs(value/1000) < 1.0){
         curr = value * 1000;
         Log.d("aTag", "getBatteryCurrentNow  if(curr < 1.0) : "+  curr);
    }

    int count = 0;
    Log.d("aTag", "getBatteryCurrentNow 2: "+  curr);
    Log.d("aTag", "getBatteryCurrentNow 3: "+  curr/1000);
    return (value != 0 && value != Integer.MIN_VALUE) ? (Double) curr/1000 : 0;

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Muhammad Ibrar