Google的官方文档中描述是只有满足执行任务的条件后,任务才会被执行。实际验证,即使条件不满足,任务也会被执行,也就是如下代码和上述代码的实际执行结果一样。
public static void scheduleJob( Context context) { JobScheduler js = ( JobScheduler) context. getSystemService( Context. JOB_ SCHEDULER_ SERVICE); JobInfo job = new JobInfo. Builder( MY_ BACKGROUND_ JOB,
new ComponentName( context, JobSchedulerService. class)) // 设置 任务 的 执行 间隔 时间 为 10 秒 . setPeriodic( 10* 1000) // 设置 设备 关机 重 启 后, 还是 继续 按 上述 要求 执行 此 任务 . setPersisted( true) . build(); js. schedule( job); } //取消 Job private void cancelJob(){ mJobScheduler. cancelAll(); } //创建 Service 类 public class JobSchedulerService extends JobService { public static final int MY_ JOB_ MESSAGE = 0; private Handler mJobHandler = new Handler( new Handler. Callback() { @ Override public boolean handleMessage( Message msg ) { Toast. makeText( getApplicationContext(), "JobService
"JobService task running", Toast. LENGTH_ LONG). show(); jobFinished( (JobParameters) msg. obj, false); return true; } } ); @ Override public boolean onStartJob( JobParameters params ) { mJobHandler. sendMessage( Message. obtain( mJobHandler, MY_ JOB_ MESSAGE, params ) ); return false; } @ Override public boolean onStopJob( JobParameters params ) { Toast. makeText( getApplicationContext(), "JobService task stop", Toast. LENGTH_ SHORT ).show(); mJobHandler. removeMessages( MY_ JOB_ MESSAGE); return false; } }