5

When my app is starting, I created a periodic work request using WorkManager to fetch the data from the server and its working fine. My problem is, I want to cancel the work request when my app is closing.

How to cancel the work request when my app is closing or how to detect the app is closing?

I would appreciate any suggestions.

stay_hungry
  • 1,448
  • 1
  • 14
  • 21
  • 1
    [1](https://android.jlelse.eu/how-to-detect-android-application-open-and-close-background-and-foreground-events-1b4713784b57) [2](https://stackoverflow.com/questions/27865016/why-manage-lifecycle-through-application-class) – denvercoder9 Sep 05 '19 at 06:15

2 Answers2

4

As mentioned in the Android Documentation.

In Kotlin

WorkManager.cancelWorkById(workRequest.id)

In Java

WorkManager.cancelWorkById(workRequest.getId());

You can also cancel WorkRequests by tag using WorkManager.cancelAllWorkByTag(String). Note that this method cancels all work with this tag. Additionally, you can cancel all work with a unique name using WorkManager.cancelUniqueWork(String).

EDIT

To check help in app closing events, check the ProcessLifecycleOwner.

Kotlin example

https://github.com/jshvarts/AppLifecycleDemo

Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
0

To can work on app close, override Activity's onDestroy() method and then cancel the current work. There are mainly two types of work

Enqueued Work

If you no longer need your previously-enqueued work to run, you can ask for it to be cancelled. The simplest way to do this is by cancelling a single WorkRequest using its id and calling

WorkManager.cancelWorkById(workRequest.getId());

OR you can also cancel work by tag.

WorkManager.cancelAllWorkByTag(String)

Running Work

There are a few different reasons your running worker may be stopped by WorkManager:

  • You explicitly asked for it to be cancelled (by calling WorkManager.cancelWorkById(UUID), for example).
  • In the case of unique work, you explicitly enqueued a new WorkRequest with an ExistingWorkPolicy of REPLACE. The old WorkRequest is immediately considered terminated.
  • Your work's constraints are no longer met.
  • The system instructed your app to stop your work for some reason. This can happen if you exceed the execution deadline of 10 minutes. The work is scheduled for retry at a later time.

Under these conditions, your worker will receive a call to ListenableWorker.onStopped().

According to your requirements, you explicitly asked for it to be cancelled (1st Point). You need to override onStopped() in your worker class and perform cleanup.

@Override
public void onStopped() {
    super.onStopped();
    //Perform cleanup
}

And in your activity onDestroy() method, stop work by either id or tag.

@Override
protected void onDestroy() {
    super.onDestroy();
    WorkManager.cancelWorkById(UUID);
}

Hope this will work. Thanks

Umer Farooq
  • 583
  • 3
  • 17