Code Finder Code Finder - 1 year ago 56
Android Question

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

I want to close my app when the battery level of the device gets low.
I have added following codes in manifest.

<receiver android:name=".BatteryLevelReceiver"
<action android:name="android.intent.action.ACTION_BATTERY_LOW" />
<action android:name="android.intent.action.ACTION_BATTERY_OKAY" />

And following code in receiver

public class BatteryLevelReceiver extends BroadcastReceiver

public void onReceive(Context context, Intent intent)
Toast.makeText(context, "BAttery's dying!!", Toast.LENGTH_LONG).show();
Log.e("", "BATTERY LOW!!");

I am running the app on emulater and changing the battery level using telnet.
It changes the battery level but not showing any toast or logs.

What am I missing??
Any help is appreciated!
Thank you.

Answer Source

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;

    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(
int level = BATTERYintent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
Log.v(null, "LEVEL" + level);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download