Thursday, 27 October 2011

Android: Getting battery status, health, level

How to get the battery level of your android device?

Let's say you want to create a battery indicator that shows that level and health. The easiest way to do it is installing a broadcast listener for the intent ACTION_BATTERY_CHANGED.

In this example code

public class BatteryChangeBroadcastReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
      int batteryLevel=intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
      int maxLevel=intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);  
      int batteryHealth=intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 
      float batteryPercentage=((float)batteryLevel/(float)maxLevel) * 100;

      //Do something with batteryPercentage and batteryHealth. 
      //batteryPercentage here ranges 0-100

onReceive runs every time the battery level changes. More details about what batteryHealth means can be found here.

The caveat here is that this broadcast  receiver can start activities, i.e, it won't work if defined in the manifest file.
You need to manually register and unregister in your app code. This means your app must be running to receive the battery status.
Here's how it would look like using the broadcast listener above.

public void onCreate(Bundle savedInstanceState) {
      mBatteryLevelReceiver=new BatteryChangeBroadcastReceiver();
      registerReceiver(mBatteryLevelReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

public void onDestroy(){

Unregistering the receiver after the app finishes is very important. You may even want to register/unregister during pause/resume.

And remember, the app must be running for this to work. I'm sure you can find a neat way of doing that ;)

Have fun