Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get battery level before broadcast receiver responds for Intent.ACTION_BATTERY_CHANGED

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?

like image 403
stealthcopter Avatar asked Sep 07 '10 18:09

stealthcopter


People also ask

What is the difference between a broadcast receiver and an intent filter?

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.

Can broadcast receiver run in background?

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.

How do you broadcast custom intents?

Sending Broadcast intents from the Activity Intent intent = new Intent(); intent. setAction("com. journaldev. CUSTOM_INTENT"); sendBroadcast(intent);


1 Answers

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

like image 187
isdal Avatar answered Sep 18 '22 08:09

isdal