Android periodic JobService never starts

2019-06-20 06:37发布

问题:

I have a JobService that I would like to start periodically. At the moment, for testing, I am using a trivial one:

public class SenderService extends JobService {

    @Override
    public boolean onStartJob(final JobParameters params) {
        new Thread(new Runnable(){
            public void run(){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                jobFinished(params, false);
            }
        }).start();

        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }
}

I schedule the job like this:

ComponentName serviceName = new ComponentName(this, SenderService.class);

JobInfo jobInfo = new JobInfo.Builder(JOB_ID, serviceName)
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        .setRequiresDeviceIdle(false)
        .setRequiresCharging(false)
        .setPersisted(true)
        .setPeriodic(10000)
        .build();

scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

int result = scheduler.schedule(jobInfo);

if (result == JobScheduler.RESULT_SUCCESS) {
    Log.d(LOGTAG, "job created");
} else {
    Log.d(LOGTAG, "job not created");
}

But the job never starts. If I remove the setPeriodic(), then it starts (but only once of course).

What is going on?