Android Workmanager PeriodicWorkRequest 不是唯一的
Android Workmanager PeriodicWorkRequest is not unique
对于 OneTimeWorkRequest,我们可以使用 WorkContinuation 来确保如果作业已经安排好了,我们可以保留或替换它。
PeriodicWorkRequest 没有这样的选项,所以每次创建我的主要 activity 时都会创建一个新作业,一段时间后我会收到此异常。
java.lang.IllegalStateException: Apps may not schedule more than 100 distinct jobs
所以我正在尝试创建一个 "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));
}
然后在工作结束时再次调用此方法
public WorkerResult doWork() {
try {
//work to be done
} catch (Exception e) {
Log.e(TAG,e.getLocalizedMessage());
return WorkerResult.FAILURE;
}
schedule();
return WorkerResult.SUCCESS;
}
另一种解决方法是将标记 REQUEST_TAG
添加到 PeriodicWorkRequestBuilder
,然后在将定期请求加入队列之前调用 WorkManager.getInstance().cancelAllWorkByTag(REQUEST_TAG)
。
您看到的 IllegalStateException
是我们在 alpha01
中修复的错误。使用 alpha02
库,您将不会看到该问题。有关详细信息,请查看发行说明 here。
对于 OneTimeWorkRequest,我们可以使用 WorkContinuation 来确保如果作业已经安排好了,我们可以保留或替换它。 PeriodicWorkRequest 没有这样的选项,所以每次创建我的主要 activity 时都会创建一个新作业,一段时间后我会收到此异常。
java.lang.IllegalStateException: Apps may not schedule more than 100 distinct jobs
所以我正在尝试创建一个 "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));
}
然后在工作结束时再次调用此方法
public WorkerResult doWork() {
try {
//work to be done
} catch (Exception e) {
Log.e(TAG,e.getLocalizedMessage());
return WorkerResult.FAILURE;
}
schedule();
return WorkerResult.SUCCESS;
}
另一种解决方法是将标记 REQUEST_TAG
添加到 PeriodicWorkRequestBuilder
,然后在将定期请求加入队列之前调用 WorkManager.getInstance().cancelAllWorkByTag(REQUEST_TAG)
。
您看到的 IllegalStateException
是我们在 alpha01
中修复的错误。使用 alpha02
库,您将不会看到该问题。有关详细信息,请查看发行说明 here。