How to detect when the Battery's low : Android?

You can register your receiver in the AndroidManifest.xml, however make sure that the action you are filtering on is

android.intent.action.BATTERY_LOW

and not

android.intent.action.ACTION_BATTERY_LOW

(which you have used in your code).


Register your receiver in the code, not in the AndroidManifest file.

registerReceiver(batteryChangeReceiver, new IntentFilter(
    Intent.ACTION_BATTERY_CHANGED)); // register in activity or service

public class BatteryChangeReceiver extends BroadcastReceiver {

    int scale = -1;
    int level = -1;
    int voltage = -1;
    int temp = -1;

    @Override
    public void onReceive(Context context, Intent intent) {
        level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
        voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
    }
}

unregisterReceiver(batteryChangeReceiver);//unregister in the activity or service

Or listen to the battery level with null receiver.

Intent BATTERYintent = this.registerReceiver(null, new IntentFilter(
        Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
Log.v(null, "LEVEL" + level);

k3v is correct.

There is actually an error in the documentation. It specifically says to use android.intent.action.ACTION_BATTERY_LOW. But the correct action to put in the manifest is android.intent.action.BATTERY_LOW See here: http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

(Couldn't vote k3v's answer up, not enough StackOverflow point things...)

UPDATE: I now can and did up-vote k3v's answer :-)

Tags:

Java

Android