Using WorkManager to download a file from the network requires initiating the download inside the setForegroundAsync method to ensure it continues even if the app is removed from the recent screen. The setForegroundAsync method runs in a thread called WM.task-1. If setForegroundAsync is not used, WorkManager runs in a thread called androidx.work-1.
The issue arises when cancelling the download from the notification. The notification dismissal only happens after the setForegroundAsync thread execution completes. As a result, the notification takes effect only after the previous thread completes its execution, since the notification runs on the main thread. Furthermore, cancelling a work by its ID using WorkManager.getInstance(context).cancelWorkById(workId) is also executed after the thread completes its execution.
If setForegroundAsync is not used then notification dismisses at expected, but download stops when cleared from recents screen