针对您的问题,举一个简单的例子,相信会对您有所帮助:
AndroidManifest.xml:
<service android:name=".YourJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
你的JobService.java:
class YourJobService extends JobService {
private static final int JOB_ID = 1;
private static final long ONE_DAY_INTERVAL = 24 * 60 * 60 * 1000L; // 1 Day
private static final long ONE_WEEK_INTERVAL = 7 * 24 * 60 * 60 * 1000L; // 1 Week
public static void schedule(Context context, long intervalMillis) {
JobScheduler jobScheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
ComponentName componentName =
new ComponentName(context, YourJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setPeriodic(intervalMillis);
jobScheduler.schedule(builder.build());
}
public static void cancel(Context context) {
JobScheduler jobScheduler = (JobScheduler)
context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.cancel(JOB_ID);
}
@Override
public boolean onStartJob(final JobParameters params) {
/* executing a task synchronously */
if (/* condition for finishing it */) {
// To finish a periodic JobService,
// you must cancel it, so it will not be scheduled more.
YourJobService.cancel(this);
}
// false when it is synchronous.
return false;
}
@Override
public boolean onStopJob(JobParameters params) {
return false;
}
}
安排好工作后,打电话YourJobService.schedule(context, ONE_DAY_INTERVAL)
。仅当连接到某个网络时并且一天进入内部一次时才会调用它......即每天连接到网络一次。
Obs.:周期性作业只能调用完成JobScheduler.cancel(Job_Id)
, jobFinished()
方法不会完成它。
Obs.:如果你想将其更改为“每周一次”-YourJobService.schedule(context, ONE_WEEK_INTERVAL)
.
obs.:定期工作安卓L可以在您设置的范围内随时运行一次。