Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android JobScheduler onStartJob called multiple times

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:

  1. onStartJob() for job 1 and job 2
  2. Both jobs finish, so jobFinished() is invoked for both of them
  3. 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.

like image 863
vRallev Avatar asked Aug 18 '15 17:08

vRallev


3 Answers

I guess it's caused by the pending Job, so I call mJobScheduler.cancelAll() after the service started, problem resolved.

like image 58
Xande Avatar answered Nov 10 '22 16:11

Xande


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.

like image 41
drmrbrewer Avatar answered Nov 10 '22 18:11

drmrbrewer


this is the problem in android lollypop and Marshmallow. It is fixed in Nougat as explained by Matthew Williams here

like image 1
Imran Khan Saifi Avatar answered Nov 10 '22 16:11

Imran Khan Saifi