loalexzzzz
loalexzzzz

Reputation: 493

WorkerManger is still auto running when app has already restarted

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()

Upvotes: 0

Views: 224

Answers (1)

pfmaggi
pfmaggi

Reputation: 6476

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.

Upvotes: 1

Related Questions