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?
An IntentFilter specifies the types of intents to which an activity, service, or broadcast receiver can respond to by declaring the capabilities of a component. BroadcastReceiver does not allows an app to receive video streams from live media sources.
A broadcast receiver will always get notified of a broadcast, regardless of the status of your application. It doesn't matter if your application is currently running, in the background or not running at all.
Sending Broadcast intents from the Activity Intent intent = new Intent(); intent. setAction("com. journaldev. CUSTOM_INTENT"); sendBroadcast(intent);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With