Android : Do something when battery is at a define

2019-03-16 21:44发布

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

        }
    }
}

2条回答
萌系小妹纸
2楼-- · 2019-03-16 21:44

ACTION_BATTERY_LOW doesn't have the Extras you're trying to read from it, so you're getting percent 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, so registerReceiver() returns the last Intent immediately. That means you can do something like:

public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals(ACTION_BATTERY_LOW)) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);

        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        int percent = (level*100)/scale; 

        if (percent <= 10 && percent > 5) {
            // Do Something
        }
    }
}

Note that registerReciever() was called with a null 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.)

查看更多
Explosion°爆炸
3楼-- · 2019-03-16 21:54

In this case, you can use "ACTION_BATTERY_CHANGED"

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
            int level = intent.getIntExtra("level", 0);
            int scale = intent.getIntExtra("scale", 100);
            double batStatus = level * 100 / scale;
        }
    }

Hope this will help you.

查看更多
登录 后发表回答