android - 检查 WorkRequest 之前是否已被 WorkManager Android 入队
问题描述
我每 15 分钟使用 PeriodicWorkRequest 为我执行一项任务。我想检查一下,这个定期工作请求是否之前已经安排好了。如果没有,请安排它。
if (!PreviouslyScheduled) {
PeriodicWorkRequest dataupdate = new PeriodicWorkRequest.Builder( DataUpdateWorker.class , 15 , TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(dataupdate);
}
以前当我使用 JobScheduler 执行任务时,我曾经使用
public static boolean isJobServiceScheduled(Context context, int JOB_ID ) {
JobScheduler scheduler = (JobScheduler) context.getSystemService( Context.JOB_SCHEDULER_SERVICE ) ;
boolean hasBeenScheduled = false ;
for ( JobInfo jobInfo : scheduler.getAllPendingJobs() ) {
if ( jobInfo.getId() == JOB_ID ) {
hasBeenScheduled = true ;
break ;
}
}
return hasBeenScheduled ;
}
需要帮助为工作请求构建类似的模块,以帮助查找计划/活动的工作请求。
解决方案
为 PeriodicWorkRequest 任务设置一些标签:
PeriodicWorkRequest work =
new PeriodicWorkRequest.Builder(DataUpdateWorker.class, 15, TimeUnit.MINUTES)
.addTag(TAG)
.build();
然后在 enqueue() 工作之前检查带有 TAG 的任务:
WorkManager wm = WorkManager.getInstance();
ListenableFuture<List<WorkStatus>> future = wm.getStatusesByTag(TAG);
List<WorkStatus> list = future.get();
// start only if no such tasks present
if((list == null) || (list.size() == 0)){
// shedule the task
wm.enqueue(work);
} else {
// this periodic task has been previously scheduled
}
但是,如果您真的不需要知道它是否已预先安排,您可以使用:
static final String TASK_ID = "data_update"; // some unique string id for the task
PeriodicWorkRequest work =
new PeriodicWorkRequest.Builder(DataUpdateWorker.class,
15, TimeUnit.MINUTES)
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork(TASK_ID,
ExistingPeriodicWorkPolicy.KEEP, work);
ExistingPeriodicWorkPolicy.KEEP 意味着任务将只安排一次,然后即使在设备重新启动后也会定期工作。如果您需要重新安排任务(例如,如果您需要更改任务的某些参数),则需要在此处使用 ExistingPeriodicWorkPolicy.REPLACE
推荐阅读
- mysql - 具有多个 AND 语句的 MySQL 查询
- docker - 带有通配符的 Dockerfile COPY 在 GitLab 管道中失败。“没有指定源文件”
- arrays - 如何通过“镜像效应”按照另一个表的顺序对表进行排序?
- php - 在颤振中从 PHP REST API 获取数据给出异常
- mongodb - mongoose - 如何从连接对象启动事务会话?总是抛出“没有交易开始”
- oracle - 如何回收 Oracle SYSAUX 表空间中未使用的空间?
- angular - 当请求在Angular中具有不同的参数时如何限制请求
- javascript - 将 JavaScript 闭包添加到图表数据刷新器
- python - 线程函数完成后重定向到不同的页面
- flutter - 垂直窗口 TabBar 菜单和颤动中的动画指示器