Gold Chicken
Gold Chicken

Reputation: 395

WorkManager not running when app is closed / killed

I am trying to run a simple work every 10 seconds using WorkManager. It works perfectly when app is running on background or foreground. When I close the app (kill the app), the work will not be called anymore.

I call the below code when MainActivity created

fun scheduleNotification(context: Context) {
    val workRequest = OneTimeWorkRequest.Builder(NotificationWorker::class.java).setInitialDelay(10000, TimeUnit.MILLISECONDS)
    WorkManager.getInstance().enqueueUniqueWork("NotificationWorker", ExistingWorkPolicy.REPLACE, workRequest.build())
    Log.d("NotificationWorker", "start")
}

The Worker class

class NotificationWorker(context: Context, params: WorkerParameters) : Worker(context, params) {

override fun doWork(): Result {
    Log.d("NotificationWorker", "Working")
    NotificationUtil.scheduleNotification(applicationContext) // n times
    return Result.success()
}
}

These code work well when my app does not closed.

How can I make it runs even when the app was closed?

Upvotes: 7

Views: 8543

Answers (2)

Ankit Verma
Ankit Verma

Reputation: 728

Periodic works Work manager only work at minimum interval of 15 minutes. If you need to do work continuously then use foreground service to define your work. Remember to put it in separate thread and a foreground service notification to keep it alive otherwise system will kill it within a minute.

Upvotes: 3

Mohsen
Mohsen

Reputation: 33

I would suggest you to use the PeriodicWorkRequest for such tasks that need to execute periodically. Check the details here.

https://developer.android.com/topic/libraries/architecture/workmanager/how-to/recurring-work

Upvotes: -3

Related Questions