Search code examples
androidkotlinbroadcastreceiverandroid-workmanager

long running service in specified time with android WorkManager


Imagine there is a switch in my application. when user switch it on, I want to run a Broadcast Receiver after five hours from that moment ,then stop the Broadcast Receiver after 8 hours.

for example if user enable the switch at 09:00 , service will enable Broadcast Receiver at 14:00 and will disable it at 22:00. in fact I want to enable the Broadcast Receiver between two time using android Work Manager but I don't know how. should I use OnetimeworkRequestBuilder or PeriodicWorkRequestBuilder and how? any suggestion?

and I show a notification to user when Broadcast Receiver is enable so I think its better to use Work Manager


Solution

  • You can't be specific with WorkManager. You need to use AlarmManager:

    Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

    https://developer.android.com/reference/android/app/AlarmManager

    These are the cases for WorkManager:

    https://developer.android.com/guide/background

    Article on AlarmManager vs WorkManager vs Service vs Background Thread:

    https://android-developers.googleblog.com/2018/10/modern-background-execution-in-android.html