让我们谈谈工作经理。
在我的应用程序中,我需要定期检索数据以避免打扰我的用户。所以我决定实施 Workmanager(在我们使用 alarmanager 之前是时候改变了!) 这是我的工作经理:
private void createPeriodicWork(Context context, Workers worker, Class<? extends ListenableWorker> workerClass,
long interval, long flexInterval, TimeUnit unit, ExistingPeriodicWorkPolicy workPolicy) {
PeriodicWorkRequest syncSurveyRequest = new PeriodicWorkRequest.Builder(
workerClass,
interval, unit,
flexInterval, unit)
.setConstraints(networkConstraint)
.build();
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
worker.getName(),
/* KEEP :If a work with this name already exists, the WorkManager
will not replace it by the new one */
workPolicy,
syncSurveyRequest
);
}
我这样称呼我的工人:
createPeriodicWork(context, Workers.SYNC_SURVEY, SyncSurveyWorker.class,
10, 8, TimeUnit.HOURS, ExistingPeriodicWorkPolicy.KEEP);
但在某些情况下,假设我的用户没有调查,我决定使用这种模式调用 OnetimeWorkRequest :
case SYNC_SURVEY:
OneTimeWorkRequest syncSurveyRequestImmediately = new OneTimeWorkRequest
.Builder(SyncSurveyWorker.class)
.setConstraints(networkConstraint)
.build();
/*
* Using "UniqueWork" function because if several "immediately" works are asked
* by the user, only one will be saved in order to launch only one work.
*/
WorkManager.getInstance(context).enqueueUniqueWork(
worker.getName() + "_immediately",
ExistingWorkPolicy.KEEP,
syncSurveyRequestImmediately);
break;
我知道从工作经理的角度来看,这是两个不同的实例,所以我的问题是防止两者同时播放的最佳方法是什么?
我考虑了一下,我的想法是:当我需要使用 oneTimeWorker 时,我需要取消周期,当我的一个 time Worker 完成时,我创建一个新的周期实例。
我坚持这个唯一的想法,您认为它们是其他最佳选择吗?
先谢谢你