Android: do something when the battery is at a certain level

I am stuck with a little problem here.

I want my application to do something, but only when the battery is at 10%.

My application does not constantly monitor the battery level; he is just waiting for the intent of LOW_BATTERY.

It works if I don’t indicate the level, but it works 3 times: 15%, 10% and 5%

I want him 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

        }
    }
}
+3
source share
2 answers

ACTION_BATTERY_LOWdoes not contain the Extra that you are trying to read, so you get it percentlike -1every time.

@bimal , ACTION_BATTERY_CHANGED. , , , . ACTION_BATTERY_CHANGED , registerReceiver() Intent. , - :

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
        }
    }
}

, registerReciever() null BroadcastReceiver, . , : " ?" (, , , , ​​.)

+6

"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;
        }
    }

, .

+3

All Articles