1

I've created custom broadcast receiver to listen for battery changes (I would like to monitor the percentage level of the battery)

However I'm not getting any updates. Here is my setup:

class MyService : IntentService("MyService") {

val receiver: PowerConnectionReceiver = PowerConnectionReceiver()

override fun onHandleIntent(intent: Intent?) {
  Timber.d("Service started now")
}

override fun onCreate() {
 val batteryStatus: Intent? = 
 IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
  registerReceiver(receiver, ifilter)
 }

}

class PowerConnectionReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {
     val status: Int = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
    Timber.d("Battery changed")
    }
  }
}
K.Os
  • 5,123
  • 8
  • 40
  • 95
  • 3
    Why is this an `IntentService`? Try logging `onDestroy()`, I'm pretty sure it gets called immediately. You should be using normal Service. – Pawel Sep 13 '18 at 12:13
  • You're right probably it is JobIntentService..... But they say on Oreo should use JobIntentService? – stuckedunderflow Jan 15 '19 at 16:58

1 Answers1

3

You will receive updates for the < 1 millisecond time that your IntentService is running. Your IntentService shuts down as soon as onHandleIntent() returns. IntentService is designed for short-term transactional sorts of work, not long-term operation.

Switch to a regular Service. Make sure that it is a foreground service (using startForeground()), as otherwise it will only run for 1 minute on Android 8.0+.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • But they say better use background service (JobIntentService + JobScheduler) compared to ForegroundService (with annoying notif) for sake of battery wise consumption? Some more if not mistaken JobScheduler can aware of battery changes. So which way "in this case" is better / recommended? – stuckedunderflow Jan 16 '19 at 03:46