I'm trying to trigger the broadcast receiver whenever the battery is low irrespective of whether the app is in the foreground/killed. The Broadcast's onReceive() is never been called. I've followed the Official doc & I've gone through almost all solutions none of them worked for me. Please let me know any other solution. Thanks :)
Manifest.xml:
<receiver
android:name=".worker.LowBatteryBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW" />
<action android:name="android.intent.action.BATTERY_OKAY" />
</intent-filter>
</receiver>
BroadcastReceiver.class
class LowBatteryBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
val level: Int = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
Timber.d("LowBatteryBroadcastReceiver - level: %d", level)
}
}
I issued the same problem, solved it by explicitly registering the receiver in my code (without removing from the manifest, but it should be ininfluent). I think it's related with the changes from SDK 26 where implicit broadcasts are no longer allowed excepts for certain types of broadcasts in which BATTERY_LOW
alas doesn't belong to.
batteryLevel = new BatteryLevel();
mContext.registerReceiver(batteryLevel, new IntentFilter(Intent.ACTION_BATTERY_LOW));
Here's reference to the official documentation