建议收boot_complte 广播重新开机 在receiver中初始化JobSchedule
5分钟后开启
public void scheduleRegularJob(Context context) { Log.d("RegularSmsJobService", "scheduleRegularJob in 5mins:"+System.currentTimeMillis()); if (VersionControlUtils.isLollipopOrLater()) { mServiceComponent = new ComponentName(context, RegularSmsJobService.class); JobInfo.Builder builder = new JobInfo.Builder(RegularJobId, mServiceComponent); //builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); builder.setMinimumLatency(4 * 60 * 1000L); builder.setOverrideDeadline(5 * 60 * 1000L); JobScheduler tm = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); PersistableBundle mBundle = new PersistableBundle(); mBundle.putString("key", "first_after_bootcomplete"); builder.setExtras(mBundle); int jobId = tm.schedule(builder.build()); LenovoSharedPreferenceUtils.setSharedPreference(context, LenovoSharedPreferenceUtils.PREF_JOBID_NETWORK, jobId); } }
一定要加setminimumLatency 不然会直接运行,setOverrideDeadline不起作用
周期运行设置的坑:
public void scheduleRegularJob(Context context) { Log.d(TAG, "schedule job 12 hours periodically"); if (VersionControlUtils.isLollipopOrLater()) { cancelAllJobs(context); mServiceComponent = new ComponentName(context, RegularSmsJobService.class); JobInfo.Builder builder = new JobInfo.Builder(RegularJobIdPeriod, mServiceComponent); //builder.setPeriodic(12 * 60 * 60 * 1000l); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { builder.setPeriodic(START_SERVICE_INTERVAL, 60 * 1000L); } else { builder.setPeriodic(START_SERVICE_INTERVAL); } JobScheduler tm = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); PersistableBundle mBundle = new PersistableBundle(); mBundle.putString("key", "regular_auto_import_birth"); builder.setExtras(mBundle); tm.schedule(builder.build()); } }
把setPeriodic 修改成5mins进行测试,发现不起作用,长期跟踪发现每15mins运行一次,很奇怪,各种baidu都没有信息,最后google了一下,发现了
I was having this problem and after review some blogs and the official documentation, I realised that JobScheduler is having difference behavior on Android N(24 and 25). JobScheduler works with a minimum periodic of 15 mins.
所以,使用setperiodic的时候一定要注意!!!!
对了另外建议, jobschedule 可以在Broadcaster Receiver中初始化,
也可以在JobService中初始化。
onStartJob
这个方法如果另外起线程做一些费事的事情的话,最好返回为true,
然后在线程运行完成后 调用jobFinished, 不然线程没执行完成,jobservice就直接onDestory了, 虽然还没看到这个有什么影响,如果你要返回结果进行加工显示就是另外的情况了。
jobFinished(params, false);