Which is the difference between two methods to calculate the battery level in android?

StackOverflow https://stackoverflow.com/questions/17574517

  •  02-06-2022
  •  | 
  •  

in my application i display the battery level.. i get the battery level in this way:

int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

And it's ok i can see the percentage.. but online i found another way:

int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float batteryPct = level / (float)scale;

What's the difference? Why i would divide the level with the scale? Thanks

有帮助吗?

解决方案

Well, you get different numbers :)

the scale is the integer containing the maximum battery level. So with the second method you get the percentage (hence it is called batteryPct) you have left. With the first you get the asolute number of your battery level. It is defined as integer field containing the current battery level, from 0 to EXTRA_SCALE.

其他提示

According to the Android docs, the SCALE is the max value:

public static final String EXTRA_SCALE

Added in API level 5 Extra for ACTION_BATTERY_CHANGED: integer containing the maximum battery level.

Constant Value: "scale"

And the LEVEL is the current level:

public static final String EXTRA_LEVEL

Added in API level 5 Extra for ACTION_BATTERY_CHANGED: integer field containing the current battery level, from 0 to EXTRA_SCALE.

Constant Value: "level"

So basically, the first gives you an absolute number and the second gives you a percentage.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top