JobScheduler - Updating job info after creating job

620 views Asked by At

I want to sync data to server after certain amount of time and this time is configurable ranging from 30 minutes to 8 hours.

I am using JobScheduler to achieve above.

Is there any way using which I can update the JobInfo associated with JobScheduler?

So that I can update value set in setPeriodic(intervalMillis) method to the updated time interval.

1

There are 1 answers

3
mralien12 On

Refer my sample code below

    int PERIODIC_SYNC_JOB_ID = 0;
    long interval  = 1000 * 60 * 20;
    JobInfo.Builder builder = new JobInfo.Builder(PERIODIC_SYNC_JOB_ID,
            new ComponentName(getApplicationContext(), SampleJobService.class));
    JobInfo jobInfo = builder.setPeriodic(interval).build();

    JobScheduler jobScheduler = (JobScheduler) getApplicationContext().getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(jobInfo);

    Log.d("JobScheduler", "Sample job is scheduled every " + interval + " ms");

SampleJobService.java

public class SampleJobService extends JobService {
@Override
public boolean onStartJob(JobParameters jobParameters) {
    Log.d("SampleJobService", "onStartJob()");

    // do something in another thread/handler/AsyncTask

    jobFinished(jobParameters, false);
    Log.d("SampleJobService", "Sample job is rescheduled");
    return true;
}

@Override
public boolean onStopJob(JobParameters jobParameters) {
    Log.d("SampleJobService", "onStopJob()");
    return false;
}

}

Remember to add your service in Manifest

        <service
        android:name=".SampleJobService"
        android:permission="android.permission.BIND_JOB_SERVICE" />

Note that minimum interval is 15 minutes. Attempting to declare a smaller period that this when scheduling a job will result in a job that is still periodic, but will run with this effective period.