fluttercommunity / flutter_workmanager

A Flutter plugin which allows you to execute code in the background on Android and iOS.
826 stars 247 forks source link

How can I cancel a task when I close the app in Android? #471

Closed nestortotembear closed 1 year ago

nestortotembear commented 1 year ago

I'm using RegisterOneOffTask and while the task is running I close the app swiping it, however after some seconds the task starts again, is there a way to cancel the task so it wont run again?

TOMER628 commented 1 year ago

Hi.

You can Try to use this Method to cancel

Cancellation # A task can be cancelled in different ways :

By Tag Cancels the task that was previously registered using this Tag, if any.

Workmanager().cancelByTag("tag");

By Unique Name Workmanager().cancelByUniqueName('Unique Name' );

ened commented 1 year ago

Once the task runs, it is more or less independent of the App on Android. To fulfil the logic you are looking for, consider setting a static variable in your MainActivity and reading that in the work manager task.

I solved this previously using my own plugin https://github.com/ened/flutter_native_app_state_plugin

If it helps you, it can be updated / published on the store.