Android Battery Monitoring

Category: 

For many applications, it might be interesting to know the current charging state of our battery. If it is almost empty, you should consider to change into a mode with lower energy consumption. Or you could do it the other way around. If your device is in charging mode, you could consume more resources and power as in normal mode.

Determine the current charging state

The BatteryManager broadcasts all battery and charging details in a sticky Intent. You could register a BroadcastReceiver to receive all changes fully automatically. But most times it's enough to periodically check the state and because it's a sticky Intent we can pass null to registerReceiver and the current battery status intent is returned.

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

This intent contains all information we need.

// Current charging state, -1 if in erroneous state
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
  || status == BatteryManager.BATTERY_STATUS_FULL;

// device plugged in?
int plug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = plug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = plug == BatteryManager.BATTERY_PLUGGED_AC;

If an Android device is connected to a computer, the data line of the usb cable is in use and Android throttles the power consumption to prevent interferences. So a maximum of 500mA is used. If we are charging only, without data exchange, the device can consume up to 2A.

Batterie Level

In some cases it's also useful to know the exact battery level. In this case, we're getting the information again via the sticky Intent.

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

float batteryPct = level / (float)scale;

The current battery level is between 0 (empty) and 1.0 (fully charged).