Android Workmanager PeriodicWorkRequest不是唯一的

时间:2018-05-20 13:04:09

标签: android-workmanager

对于OneTimeWorkRequest,我们可以使用WorkContinuation来确保如果作业已经安排,我们可以保留或替换它。 PeriodicWorkRequest没有这样的选项,因此每次创建主活动时都会创建一个新作业,一段时间后我会得到此异常。

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

所以我正在尝试以下方法来创建“独特的peiodic作品”

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

然后在工作结束时再次调用此方法

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

2 个答案:

答案 0 :(得分:4)

另一种解决方法是将标记REQUEST_TAG添加到PeriodicWorkRequestBuilder,然后在排队定期请求之前调用WorkManager.getInstance().cancelAllWorkByTag(REQUEST_TAG)

答案 1 :(得分:0)

您看到的IllegalStateException是我们在alpha01中修复的错误。使用alpha02库,您将无法看到该问题。有关更多信息,请查看发行说明here