首页 > 解决方案 > 检查 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 ;
}

需要帮助为工作请求构建类似的模块,以帮助查找计划/活动的工作请求。

标签: androidandroid-jetpackandroid-workmanager

解决方案


为 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


推荐阅读