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