I'm stuck with a little problem here.
I want my app to do something, but only when the battery is at 10%.
My app doesn't watch the battery level constantly; it just waits for a LOW_BATTERY intent.
It works if i don't specify a level, but it works 3 times: 15%, 10%, and 5%
I only want it to do something at 10%.
Here is my code :
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals(ACTION_BATTERY_LOW))
{
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level*100)/scale;
if(percent == 10)
{
// Do Something
}
}
}
ACTION_BATTERY_LOW
doesn't have the Extras you're trying to read from it, so you're gettingpercent
as-1
every time.As @bimal hinted at, those Extras are attached to the
ACTION_BATTERY_CHANGED
Broadcast. That doesn't mean, however, that you should just register to receive that instead.ACTION_BATTERY_CHANGED
is sticky, soregisterReceiver()
returns the last Intent immediately. That means you can do something like:Note that
registerReciever()
was called with anull
BroadcastReceiver, so you don't have to worry about unregistering. This is a nice, clean way to just say "What is the battery status right now?" (Well, technically, it's what was it last time a Broadcast was sent.)In this case, you can use "ACTION_BATTERY_CHANGED"
Hope this will help you.