如何从WorkManager Android取消工作?

时间:2018-11-23 05:34:38

标签: android realm android-workmanager

我已将作品UUID保存为Realm中的String

这是代码-

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();
            }

现在,我正在尝试使用此行代码取消Work,但没有用。

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

任何帮助将不胜感激

谢谢

1 个答案:

答案 0 :(得分:2)

如果您使用的是Worker,则需要覆盖onStopped()方法,并将其用作工人取消其正在进行的工作的信号。在您的doWork()方法中,您还可以使用isStopped()检查取消。