在Lollipop及以上版本中(即API版本21),您可以使用
JobScheduler
来安排
JobService
。为了每分钟重复一个作业,您需要在每次作业完成后设置最小延迟为60*1000毫秒以安排作业。
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MyJobService extends JobService {
boolean isWorking = false;
boolean jobCancelled = false;
@Override
public boolean onStartJob(JobParameters params) {
Log.d("_____TAG_____", "MyJobService started!");
isWorking = true;
doWork(params);
return isWorking;
}
private void doWork(JobParameters params) {
if (jobCancelled)
return;
Log.d("_____TAG_____", "MyJobService finished!");
isWorking = false;
boolean needsReschedule = false;
jobFinished(params, needsReschedule);
scheduleRefresh();
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d("_____TAG_____", "MyJobService cancelled before being completed.");
jobCancelled = true;
boolean needsReschedule = isWorking;
jobFinished(params, needsReschedule);
return needsReschedule;
}
private void scheduleRefresh() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ComponentName componentName = new ComponentName(getApplicationContext(), MyJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(5, componentName);
builder.setMinimumLatency(60*1000);
JobInfo jobInfo = builder.build();
JobScheduler jobScheduler = (JobScheduler)getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("_____TAG_____", "MyJobService scheduled!");
} else {
Log.d("_____TAG_____", "MyJobService not scheduled");
}
}
}
}
您可以编写一个公共函数,在任何您喜欢的地方,用于首次调度作业-
public void scheduleMyJobService() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
ComponentName componentName = new ComponentName(context, MyJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(5, componentName);
builder.setMinimumLatency(60*1000);
JobInfo jobInfo = builder.build();
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("_____TAG_____", "MyJobService scheduled!");
} else {
Log.d("_____TAG_____", "MyJobService not scheduled");
}
}
}