android studio workmanager once a day at a specific hour

Viewed 667

I'm trying to make an app that make a web request once a day and then push a notification with work manager.
Now, I managed to do everything except the part with the scheduling of the workmanager.
I want it to happen once a day at 8:00 am, but I couldn't figure out how.
Currently I'm using oneTimeWorkRequest, but I'll change it if there is a better option...
So what do you think is the best sulotion for my problem?

1 Answers

// In onCreate you just call startWork(); you can change attributes in createConstraints() as you want

   private fun createConstraints() = Constraints.Builder()
    .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
    .setRequiresCharging(false)
    .setRequiresBatteryNotLow(true)
    .build()


private fun createWOrkRequest() = PeriodicWorkRequestBuilder<NotifyWorker>(24, TimeUnit.HOURS)
    .setConstraints(createConstraints())
    .setInitialDelay(delay, TimeUnit.MILLISECONDS)

    .build()

private val delay = //TODO - here you have to calculate delay in order to start Worker at desired time. You can

//calculate amount of time (milliseconds) between now and 8 hours 'o clock

private fun startWork(){
    WorkManager.getInstance(this)
        .enqueueUniquePeriodicWork(
            "Some-Unique-Name",
            ExistingPeriodicWorkPolicy.KEEP,
            createWOrkRequest()
        )
}

Inside class NotifyWorker you call -sendNotification()

class NotifyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

override fun doWork(): Result {
    sendNotification()
    return Result.success()
}

private fun sendNotification(){
 // Here you create notification
}
}

That is one way to do it, old-fashioned way is to use AlarmManagers and BroadcastReceiver()...

Related