How to cancel Work from WorkManager in Android?

两盒软妹~` 提交于 2020-07-21 04:26:07

问题


I have saved the WorkManager UUID converted to String in Realm database.

Here is the code -

Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
            Data inputData = new Data.Builder().putString("downloadUrl", downloadUrl).
                    putString("destinationFolder", destinationFolder).
                    putInt("suraNumber", Integer.parseInt(suraNumber)).
                    putString("fileName", fileName).
                    putBoolean("downloadFileTypeBangla", downloadFileTypeBangla).
                    putBoolean("downloadFileTypeArabic", downloadFileTypeArabic).
                    putBoolean("downloadFileTypeArabicWithBangla", downloadFileTypeArabicWithBangla).build();
            OneTimeWorkRequest downloadWork = new OneTimeWorkRequest.Builder(DownloadWorker.class).setConstraints(constraints).setInputData(inputData).build();
            WorkManager.getInstance().enqueue(downloadWork);

            Sura sura = dbOperations.getSuraById(Integer.parseInt(suraNumber));
            if(sura != null){
                dbOperations.updateSura(sura, Integer.parseInt(suraNumber), sura.getBnAudioDownloadStatus(), sura.getArAudioDownloadStatus(), 1);
                realm.beginTransaction();
                DownloadStatusModel downloadStatusModel = new DownloadStatusModel();
                downloadStatusModel.setId(new RealmCommonService(realm).newId(DownloadStatusModel.class));
                downloadStatusModel.setDownloadFileType("ArabicWithBangla");
                downloadStatusModel.setActiveStatus(true);
                downloadStatusModel.setDownloadDate(new Date());
                downloadStatusModel.setDownloadedSuraNo(sura.getSuraNo());
                downloadStatusModel.setDownloadFileSize(sura.getArBnAudioFileSize());
                downloadStatusModel.setDownloadReferenceId(downloadWork.getId().toString());
                downloadStatusModel.setDownloadedSuraNameBangla(sura.getSuraNameBangla());
                downloadStatusModel.setDownloadStatus(1);
                realm.copyToRealm(downloadStatusModel);
                realm.commitTransaction();
            }

Now I'm trying to cancel the Work using this line of code but didn't work.

WorkManager.getInstance().cancelWorkById(UUID.fromString(downloadStatusModel.getDownloadReferenceId()));

Any help would be appreciated

Thanks


回答1:


If you're using Worker, you need to override the onStopped() method and use that as the signal for your worker to cancel its ongoing work. Within your doWork() method, you can also use isStopped() to check for cancellation.



来源:https://stackoverflow.com/questions/53441122/how-to-cancel-work-from-workmanager-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!