简体   繁体   English

evernote android-job:什么时候是正确的时间表?

[英]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 谢谢

You should create JobCreator which will instantiate your Job class like this: 您应该创建JobCreator,它将实例化Job类,如下所示:

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() : 并在Application.onCreate()初始化它:

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

MyJob may look like this: MyJob可能看起来像这样:

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();
    }
}

Extending shmakova's answer, you may need to add a condition if your sync job is already scheduled like this: 扩展shmakova的答案,如果您的同步作业已经这样安排,则可能需要添加条件:

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 这样可以避免安排多个作业

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM