WorkManager 向 JobScheduler 添加了太多作业

WorkManager adding too many jobs to JobScheduler

我正在尝试使用 WorkManager 在特定时间将任务安排到 运行。我正在使用 beginUniqueWork,因为我只想一次为该特定 ID (uniqueWorkName) 安排一个任务。但是在多次调用 enqueue 之后,在某些时候我收到以下错误:

java.lang.IllegalStateException: Apps may not schedule more than 100 distinct jobs
    at android.os.Parcel.readException(Parcel.java:2012)
    at android.os.Parcel.readException(Parcel.java:1950)
    at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:180)
    at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
    at androidx.work.impl.background.systemjob.SystemJobScheduler.scheduleInternal(SystemJobScheduler.java:85)
    at androidx.work.impl.background.systemjob.SystemJobScheduler.schedule(SystemJobScheduler.java:64)
    at androidx.work.impl.Schedulers.scheduleInternal(Schedulers.java:98)
    at androidx.work.impl.Schedulers.schedule(Schedulers.java:69)
    at androidx.work.impl.WorkManagerImpl.rescheduleEligibleWork(WorkManagerImpl.java:398)
    at androidx.work.impl.utils.ForceStopRunnable.run(ForceStopRunnable.java:66)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)

当我在每次 enqueue 后使用以下代码片段记录待处理作业的数量时,我注意到每次调用都有 3 个新作业添加到列表中(而我希望总数保持在 1 ).

JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
int size = jobScheduler.getAllPendingJobs().size();

这是我用来安排任务的代码:

val work = OneTimeWorkRequest.Builder(workerClass)
        .setInitialDelay(offset, TimeUnit.MILLISECONDS)
        .build()
WorkManager.getInstance()
        .beginUniqueWork(uniqueNameForTask, ExistingWorkPolicy.REPLACE, work)
        .enqueue()

这里有什么不对劲吗?我错过了什么?

根据 WorkManager 1.0.0-alpha07 release notes,1.0.0-alpha07 的修复之一是:

Work that has finished execution now correctly cancels all pending copies of that work in other Schedulers. This led to exceeding the JobScheduler jobs limit. b/111569265

所以升级到 1.0.0-alpha07 应该可以解决您的问题。