问题
The JobScheduler calls onStartJob()
multiple times, although the job finished. Everything works fine, if I schedule one single job and wait until it has finished. However, if I schedule two or more jobs with different IDs at the same time, then onStartJob()
is called again after invoking jobFinished()
.
For example I schedule job 1 and job 2 with exactly the same parameters except the ID, then the order is:
onStartJob()
for job 1 and job 2- Both jobs finish, so
jobFinished()
is invoked for both of them - After that
onStartJob()
is called again for both jobs with the same ID
My job is very basic and not complicated.
public class MyJobService extends JobService {
@Override
public boolean onStartJob(final JobParameters params) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// do something
} finally {
// do not reschedule
jobFinished(params, false);
}
}
}).start();
// yes, job running in the background
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
// mark my background task as stopped
// do not reschedule
return false;
}
}
I schedule the jobs like this
JobInfo jobInfo = createBaseBuilder(request)
.setMinimumLatency(2_000L)
.setOverrideDeadline(4_000L)
.setRequiresCharging(false)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build();
int scheduleResult = mJobScheduler.schedule(jobInfo);
// is always success
I don't know what's wrong.
回答1:
I guess it's caused by the pending Job, so I call mJobScheduler.cancelAll() after the service started, problem resolved.
回答2:
I think this relates to the Android bug reported here, which has apparently been fixed for Android N but will be present in earlier versions.
The OP is using a setOverrideDeadline()
. My understanding of the issue reported in the linked post above is that if the job is running when the override deadline fires, it causes the job to be scheduled to run again.
So the advice is to ensure that the override fires either before the job is scheduled (not sure how that is achieved) or after it has finished. Neither seems particularly satisfactory, but at least it seems to have been fixed in Android N.
回答3:
this is the problem in android lollypop and Marshmallow. It is fixed in Nougat as explained by Matthew Williams here
来源:https://stackoverflow.com/questions/32079407/android-jobscheduler-onstartjob-called-multiple-times