Get battery level before broadcast receiver responds for Intent.ACTION_BATTERY_CHANGED

stealthcopter picture stealthcopter · Sep 7, 2010 · Viewed 32.1k times · Source

I have a broadcast receiver in my program to get react to the battery level like so:

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent intent) {
        int level = intent.getIntExtra("level", 0);
        // do something...
    }
}

    registerReceiver(this.mBatInfoReceiver, 
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

However this code has to wait for the battery status to be updated so if you have a GUI element that needs to be set based on the battery level it must wait for a battery event to occur. Is there a way to nudge this to get it working or simply run some code to see what the battery level was on the last broadcast?

Answer

isdal picture isdal · Oct 29, 2010

This is how to get the battery level without registering a receiver:

Intent batteryIntent = context.getApplicationContext().registerReceiver(null,
                    new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
double scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
double level = -1;
if (rawlevel >= 0 && scale > 0) {
    level = rawlevel / scale;
}

It can use a null BroadcastReceiver because of the sticky nature of the broadcast.

It uses the getApplicationContext() trick in case you are in a intent receiver and get the exception:

android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to register to receive intents