Dnyaneshwar Patil
Dnyaneshwar Patil

Reputation: 112

Trigger BroadcastReceiver when low battery in Android

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)

    }
}

Upvotes: 1

Views: 1540

Answers (1)

LM_IT
LM_IT

Reputation: 197

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

Upvotes: 1

Related Questions