0

I want my android app to show notification when the battery level is above certain percentage which is similar to low battery notification in android. Not by assigning a background task which keeps checking battery level in background between every minute. I Just want to trigger notification when battery level is above certain percent even if the app is not running. Can I do this using broadcast receiver? any suggestions?

Gimuser39
  • 87
  • 9
  • 1
    https://developer.android.com/training/monitoring-device-state/battery-monitoring – gtxtreme Sep 05 '21 at 05:30
  • You can get the battery percent as mentioned above and then fire your own receiver and show a notification inside `onReceive` of the `BroadcastReceiver` – gtxtreme Sep 05 '21 at 05:31

1 Answers1

0

Broadcast Receiver class

class BatteryBroadcastReceiver : BroadcastReceiver() {
     override fun onReceive(context: Context, intent: Intent?) {
        val level: Int = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
        Timber.d("battery - level: %d", level)

    }
}

In Activity/Fragment register your broadcast

val batteryLevel = BatteryBroadcastReceiver();
registerReceiver(batteryLevel, new IntentFilter(Intent.ACTION_BATTERY_LOW));
  • Thanks for answering my question, But there is a mistake in your answer registerReceiver(batteryLevel, IntentFilter(Intent.ACTION_BATTERY_CHANGED)); is correct instead of registerReceiver(batteryLevel, new IntentFilter(Intent.ACTION_BATTERY_LOW));. .But this also works when app is running and do not works when the app is closed. I want to get notification even if the app is closed – Gimuser39 Sep 06 '21 at 08:26
  • I think it's related with the changes from SDK 26 where implicit broadcasts are no longer allowed excepts for certain types of broadcasts. [Here](https://developer.android.com/about/versions/oreo/background#broadcasts) in offical doc – Dnyaneshwar Patil Sep 11 '21 at 11:05
  • Yes but this can be done using foreground service – Gimuser39 Sep 13 '21 at 13:49
  • Yes, you can use the foreground service. – Dnyaneshwar Patil Sep 13 '21 at 14:01