Search code examples
androidbroadcastreceiveralarmmanagerintentserviceandroid-jobscheduler

State-of-the-art method for ongoing, frequently updating notifications ("notification widget")


I am struggling to find a current state-of-the-art method for notifications that are frequently updated (e.g. every 3 minutes). There seem to have been so much power efficiency tweaks built into newer Android versions (fortunately!), that the method I earlier successfully used (using BroadcastReceiver and AlarmManager.setRepeating) does not seem to reliably work anymore on my newer phone (running with Android 8). At some point, the notification will not get updated anymore (e.g. after the screen has been off for a couple of minutes).

Now I have stumbled acrossmany different approaches in order to address this issue, that I am a little bit lost between them, e.g:

  • using a chain of AlarmManager.setAndAllowWhileIdle instead of setRepeating
  • using WakefulBroadcastReceivers (being already deprecated again though)
  • using an IntentService instead of a BroadcastReceiver
  • using a JobIntentService instead of a IntentService
  • using the JobScheduler instead of AlarmManager

Did anyone find a reliable way in order to frequently update a status bar notification? For me, it is not important to update it exactly every X seconds, it just should happen every few minutes and not being randomly broken after the device has been in deep sleep for some time.


Solution

  • I do not really understand why this question got downvoted because in my opinion there are legit reasons for the confusion if you stumble across all those different methods and it would have really saved me some time if somebody had shared his or her experience with me.

    I understand that this question is difficult to answer, because of all the different manufacturers and phones, all including different types of power saving tweaks. But anyway, here is what I came up with after some time. The problem in my case was that in Android 8+, Google has strongly limited the granted possibility to do work for BroadcastReceivers, IntentServices and such in favor of using the JobScheduler. This makes it mandatory to use JobIntentService, providing the needed features for Android 8+ as well as backwards-compatibility for Android versions < 8.

    tl;dr:

    • Have a JobIntentService, where you what you have to do inside onHandleWork
    • Have a BroadcastReceiver, where in onReceive() you just call your JobIntentService's enqueueWork() method.
    • Use the AlarmManager inside JobIntentService#onHandleWork() in order to schedule (e.g. using setInexactRepeating()) and cancel a PendingIntent broadcast for your BroadcastReceiver.