我没有找到关于这个主题的任何内容,但我很好奇你的建议或"最佳做法"关于何时设置规则以安排任务?例如,如果我必须安排同步作业,只要应用程序运行,该作业应始终存在,
new JobRequest.Builder("...")..
.build()
.schedule()
被称为?
谢谢
答案 0 :(得分:1)
您应该创建JobCreator,它将实例化您的Job类,如下所示:
public class MyJobCreator implements JobCreator {
@Override
public Job create(String tag) {
if (MyJob.TAG.equals(tag)) {
return new MyJob();
}
return null;
}
}
并在Application.onCreate()
中初始化:
JobManager.create(this).addJobCreator(new MyJobCreator());
MyJob.scheduleJob();
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();
}
}
答案 1 :(得分:1)
扩展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();
}
}
这将阻止安排多个工作