Reputation: 22173
I want to use the android JobScheduler
to schedule one or more jobs. The problem is the job id. How can I select a differnt job every time? If I schedule new work with the same id, the old job is removed. I would need something like the enqueuWork
but you need Api level 26, my min api level is 21. How can I do that? Every work is related to the same job, for example: send mail. It's just one job, but it can have several instances.
Upvotes: 1
Views: 2715
Reputation: 544
You can use JobScheduler
's getAllPendingJobs()
method to find out an available jobID
. It will return all scheduled pending jobs, while they are pending/running. JobSchedulerService
removes a job from this list once it has finished/completed.
Obs.: Android doc describes: "Retrieve all jobs for this package that are pending in the
JobScheduler
."
I have tested this method (on Android
M and N) and it also returns the Jobs that are running. The job has removed when it is completed. In Android Source Code, getAllPendingJobs()
uses mJobs
(stores all the scheduled jobs) to return a job list. When the Job is Stopped, it is removed from mJobs
, and it is not returned in getAllPendingJobs ()
.
Upvotes: 3
Reputation: 2004
Not sure if JobScheduler has that option but if you are able to change it for another component I would recommend you : FireBase JobDispatcher
It has this option: .setReplaceCurrent(false)
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(MyJobService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// one-off job
.setRecurring(false)
// don't persist past a device reboot
.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(0, 60))
// don't overwrite an existing job with the same tag
.setReplaceCurrent(false)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on an unmetered network
Constraint.ON_UNMETERED_NETWORK,
// only run when the device is charging
Constraint.DEVICE_CHARGING
)
.setExtras(myExtrasBundle)
.build();
dispatcher.mustSchedule(myJob);
I had to use it and it works very well
Upvotes: 1