Bha*_*ani 10 android android-jetpack android-workmanager
我使用PeriodicWorkRequest每15分钟为我执行一次任务.我想检查一下这个定期工作请求是否已经预定过.如果没有,请安排它.
if (!PreviouslyScheduled) {
PeriodicWorkRequest dataupdate = new PeriodicWorkRequest.Builder( DataUpdateWorker.class , 15 , TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(dataupdate);
}
Run Code Online (Sandbox Code Playgroud)
以前当我使用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 ;
}
Run Code Online (Sandbox Code Playgroud)
需要帮助构建用于工作请求的类似模块以帮助查找计划/活动工作请求.
Ale*_*lex 20
将一些Tag设置为PeriodicWorkRequest任务:
PeriodicWorkRequest work =
new PeriodicWorkRequest.Builder(DataUpdateWorker.class, 15, TimeUnit.MINUTES)
.addTag(TAG)
.build();
Run Code Online (Sandbox Code Playgroud)
然后在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
}
Run Code Online (Sandbox Code Playgroud)
但是如果你真的不需要知道它是否曾经安排过,你可以使用:
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);
Run Code Online (Sandbox Code Playgroud)
ExistingPeriodicWorkPolicy.KEEP表示该任务只安排一次,然后即使在设备重启后也会定期工作.如果您需要重新安排任务(例如,如果您需要更改任务的某些参数),则需要在此处使用ExistingPeriodicWorkPolicy.REPLACE
| 归档时间: |
|
| 查看次数: |
4161 次 |
| 最近记录: |