Thursday, 5 April 2012

Retrieve the battery level

Each time the level of the battery changes, the system broadcast an event with the new values to all registered receivers. This notification is sent with a sticky broadcast. This kind of broadcast offers the particularity of  immediately returning the last intent sent when you register to it, so you won't have to wait for the next notification.
This sample code shows how you can retrieve the battery level:

//Retrieve the percentage of the battery level

public int getBatteryLevel(Context context) {

       //Get the sticky intent

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

       //Compute the battery level

       int level = bat.getIntExtra("level", 0);

       int scale = bat.getIntExtra("scale", 100);

       return level * 100 / scale;

}

No comments:

Post a Comment