Android Workmanager PeriodicWorkRequest is not unique

断了今生、忘了曾经 提交于 2019-11-30 16:01:41

问题


For OneTimeWorkRequest we can use WorkContinuation to ensure that if the job is already scheduled we can KEEP or REPLACE it. There is no such option for PeriodicWorkRequest, so every time my main activity is created a new job is created and after a while I get this exception.

java.lang.IllegalStateException: Apps may not schedule more than 100 distinct jobs

So I'm trying the following to create a "unique peiodic work"

public void schedule(){
    Constraints constraints = new Constraints.Builder().setRequiresBatteryNotLow(true).build();
    OneTimeWorkRequest zombieSpawnWorker = new OneTimeWorkRequest.Builder(ZombieSpawnWorker
            .class).setInitialDelay(15, TimeUnit.MINUTES).setConstraints(constraints).addTag(ZombieSpawnWorker.TAG).build();
    this.setUuid(zombieSpawnWorker.getId());
    WorkManager.getInstance().beginUniqueWork(TAG,
                    ExistingWorkPolicy.KEEP,
                    OneTimeWorkRequest.from(ZombieSpawnWorker.class));
}

And then calling this method again at the end of the work

public WorkerResult doWork() {
    try {
        //work to be done
    } catch (Exception e) {
        Log.e(TAG,e.getLocalizedMessage());
        return WorkerResult.FAILURE;
    }
    schedule();
    return WorkerResult.SUCCESS;
}

回答1:


The IllegalStateException you see was a bug we fixed in alpha01. Use the alpha02 library, and you won't see that problem. For more information, take a look at the release notes here.




回答2:


Another workaround is to add a tag REQUEST_TAG to the PeriodicWorkRequestBuilder, and then call WorkManager.getInstance().cancelAllWorkByTag(REQUEST_TAG) before you enqueue the periodic request.



来源:https://stackoverflow.com/questions/50435131/android-workmanager-periodicworkrequest-is-not-unique

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