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?
You can call
registerReceiver()with yourIntentFilterand anullBroadcastReceiverto get the last-broadcastIntent. This works becauseACTION_BATTERY_CHANGEDis a so-called “sticky broadcast”, which I describe a bit more in this StackOverflow question-and-answer.