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"
<intent-filter>
<action android:name="android.intent.action.ACTION_BATTERY_LOW" />
<action android:name="android.intent.action.ACTION_BATTERY_OKAY" />
</intent-filter>
</receiver>
And following code in receiver
public class BatteryLevelReceiver extends BroadcastReceiver
{
@Override
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!
Register using context register. If you are targeting Android 8.0 or higher, you cannot use manifest declared receiver. Paste this code in your main activity to register.
BroadcastReceiver receiver = new BatteryLevelReceiver();
IntentFilter filter =new IntentFilter(BatteryManager.EXTRA_BATTERY_LOW);
filter.addAction(Intent.ACTION_BATTERY_LOW);
this.registerReceiver(receiver, filter);
and you are good to go PS the emulator should not be in charging state
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With