alarmmanagerandroid-alarmsandroid-broadcastreceiverandroid-wake-lockandroid-jobscheduler

AlarmManager or JobScheduler compatible with all Android versions?


I need some help deciding which classes to adopt in my app that has to fulfill these requirements:

I've coded a small demo with AlarmManager & BroadcastReceiver to get an understanding of how all of this works. I've studied the docs for AlarmManager, BroadcastReceiver, WakefulBroadcastReceiver, and JobScheduler and even though I understand the differences, I don't know which one(s) will satisfy my requirements.

From the documentation, I get the impression that I might need to write multiple versions of my app to accommodate the different Android versions it will run on. This would be a nightmare!

Any suggestions on which classes to use? I would hate to go in one given direction only to later find out that I need to rewrite everything.

Thanks!


Solution

  • You don't need multiple versions of your app, you just need multiple "scheduler" implementations, each with just a couple files, and all call the same app logic.

    Well, there's only one option that handles this. You need an AlarmManager.setExact. This is strongly discouraged, because it tends to waste battery.

    Every option there handles that, as long as you give them different ids.

    Sounds like you need to have your alarm call Context.StartForegroundService, and leave that foreground service running until the user completes the task. Again, this is discouraged, because it wastes battery.

    AlarmManager and foreground services run on all versions of Android, though the call to start a foreground Service has changed slightly with Android O, the concept is identical.


    While your app is doing something important that needs to execute RIGHT NOW, even if the screen is off, then you should grab a wakelock. A wakelock prevents the CPU from pausing itself, so that you can process what needs to immediately occur. If the code can wait until the screen is turned on, then please do not use a wake lock. JobService grabs a wakelock always, so JobService code does not need to grab a separate wakelock. If you have no service running, including a JobService, then Android will randomly stop your app, even if you have a wakelock. So you always need a service of some sort, while doing any important work.