0

I found that when worker is running on the app and then force close it, after that I re-open the app, but the worker is still auto re-running from background without my control...

How can I prevent this issue? How can I cancel this worker?

val work = OneTimeWorkRequest
        .Builder(DownloadImageWorker::class.java)
        .build()

    WorkManager.getInstance(App.instance)
        .beginWith(work).enqueue()

1 Answer 1

1

WorkManager is for task that needs a guarantee to be run. The behavior you are describing is as designed.

You may want to evaluate other solutions if you don't need to persist a task in this way like Kotlin's Coroutines. You can find more on the Android's background guide.

An option with WorkManager is to manually cancel your WorkRequest. Starting from your code:

val work = OneTimeWorkRequest
        .Builder(DownloadImageWorker::class.java)
        .build()

val workManager = WorkManager.getInstance(App.instance)
workManager.beginWith(work).enqueue()

You can then cancel the workrequest when you need:

// Cancel the WorkRequest
workManager.cancelWorkById(work.id)

You can find additional information on WorkManager's documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.