Get battery level only once using Android SDK

Karlen Kishmiryan picture Karlen Kishmiryan · Apr 1, 2013 · Viewed 34.2k times · Source

I've searched on the web and couldn't find the answer to my question. My problem is to get the battery level information only once, eg. calling the function getBatteryLevel(). There are only solutions which are implemented using BroadcastReceiver, but as I know it will be called every time on battery level's change event. Please, tell me how can I get that information only once?

Answer

Michael Celey picture Michael Celey · Apr 1, 2013

The Intent.ACTION_BATTERY_CHANGED broadcast is what's known as a "sticky broadcast." Because this is sticky, you can register for the broadcast with a null receiver which will only get the battery level one time when you call registerReceiver.

A function to get the battery level without receiving updates would look something like this:

public float getBatteryLevel() {
    Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    // Error checking that probably isn't needed but I added just in case.
    if(level == -1 || scale == -1) {
        return 50.0f;
    }

    return ((float)level / (float)scale) * 100.0f; 
}

More data can be pulled from this sticky broadcast. Using the returned batteryIntent you can access other extras as outlined in the BatteryManager class.