对于 OneTimeWorkRequest,我们可以使用 WorkContinuation 来确保如果作业已经安排好了,我们可以保留或替换它。PeriodicWorkRequest 没有这样的选项,因此每次创建我的主要活动时都会创建一个新作业,一段时间后我会遇到此异常。
java.lang.IllegalStateException: Apps may not schedule more than 100 distinct jobs
所以我正在尝试以下创建一个“独特的周期性工作”
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;
}