thehayro
thehayro

Reputation: 1536

evernote android-job: When is the right time to set the schedule rules?

I did not find anything about this topic, however I am curious what your recommendations or "best practices" are regarding when to set the rules to schedule the task? For example if I have to schedule a sync job, which should always be there as long as the app runs, where would the

new JobRequest.Builder("...")..
  .build()
  .schedule()

be called?

Thank you

Upvotes: 0

Views: 882

Answers (2)

rehman_00001
rehman_00001

Reputation: 1600

Extending shmakova's answer, you may need to add a condition if your sync job is already scheduled like this:

public static void scheduleJob() {
    if (JobManager.instance().getAllJobRequestsForTag(MyJob.TAG).isEmpty()) {
        new JobRequest.Builder(MyJob.TAG)
                .setPeriodic(900_000L)
                .setRequiredNetworkType(JobRequest.NetworkType.ANY)
                .setPersisted(true)
                .setUpdateCurrent(true)
                .setRequirementsEnforced(true)
                .build()
                .schedule();
    }
}

this will prevent scheduling multiple jobs

Upvotes: 1

shmakova
shmakova

Reputation: 6426

You should create JobCreator which will instantiate your Job class like this:

public class MyJobCreator implements JobCreator {

    @Override
    public Job create(String tag) {
        if (MyJob.TAG.equals(tag)) {
            return new MyJob();
        }

        return null;
    }
}

And initialize it in Application.onCreate():

JobManager.create(this).addJobCreator(new MyJobCreator());
MyJob.scheduleJob();

MyJob may look like this:

public class MyJob extends Job {

    public static final String TAG = "my_job_tag";

    @Override
    @NonNull
    protected Result onRunJob(Params params) {
        Intent i = new Intent(getContext(), MyService.class);
        getContext().startService(i);
        return Result.SUCCESS;
    }

    public static void scheduleJob() {
        new JobRequest.Builder(MyJob.TAG)
                .setPeriodic(60_000L) // 1 minute
                .setRequiredNetworkType(JobRequest.NetworkType.ANY)
                .setPersisted(true)
                .setUpdateCurrent(true)
                .setRequirementsEnforced(true)
                .build()
                .schedule();
    }
}

Upvotes: 1

Related Questions