Android : Do something when battery is at a defined level

前端 未结 2 1826
北海茫月
北海茫月 2021-02-06 17:18

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;

2条回答
  •  感动是毒
    2021-02-06 17:30

    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.)

提交回复
热议问题