JobScheduler、JobInfo、JobService三角关系

JobScheduler是Android L(API21)新增的特性,该框架将在执行作业(也就是JobInfo)时智能化,并尽可能地批量并推迟JobInfo,从而节省电量。Android8.0及以上建议使用JobScheduler来启动服务。
JobScheduler是作业发布器,它的任务是分发设置作业JobInfo。JobInfo是作业包装体,它包含了任务执行的条件、开始时间、截止时间、具体任务、需要传递的参数等信息。JobService是JobInfo中的参数,它们是条件到了真正执行具体任务。
一、JobScheduler
JobScheduler是一个抽象类,其实例可以通过 Context.getSystemService(Context.JOB_SCHEDULER_SERVICE) 或者   Context.getSystemService( JobScheduler.class ) 来创建。
JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
JobScheduler scheduler =context.getSystemService(JobScheduler.class);
JobScheduler的主要方法及介绍见下图
二、JobInfo
JobInfo通过Builder模式 JobInfo.Builder 创建实例, JobInfo.Builder 可以设置多个参数,其中作业启动条件必须限制一个。
JobInfo.Builder 提供了很多参数来构建 JobInfo
Public methods
JobInfo.Builder addTriggerContentUri(JobInfo.TriggerContentUri uri)Add a new content: URI that will be monitored with a ContentObserver, and will cause the job to execute if changed.
JobInfo build()
JobInfo.Builder setBackoffCriteria(long initialBackoffMillis, int backoffPolicy)Set up the back-off/retry policy.
JobInfo.Builder setClipData(ClipData clip, int grantFlags)Set a ClipData associated with this Job.
JobInfo.Builder setEstimatedNetworkBytes(long downloadBytes, long uploadBytes)Set the estimated size of network traffic that will be performed by this job, in bytes.
JobInfo.Builder setExtras(PersistableBundle extras)Set optional extras.
JobInfo.Builder setImportantWhileForeground(boolean importantWhileForeground)Setting this to true indicates that this job is important while the scheduling app is in the foreground or on the temporary whitelist for background restrictions.
JobInfo.Builder setMinimumLatency(long minLatencyMillis)Specify that this job should be delayed by the provided amount of time.
JobInfo.Builder setOverrideDeadline(long maxExecutionDelayMillis)Set deadline which is the maximum scheduling latency.
JobInfo.Builder setPeriodic(long intervalMillis)Specify that this job should recur with the provided interval, not more than once per period.
JobInfo.Builder setPeriodic(long intervalMillis, long flexMillis)Specify that this job should recur with the provided interval and flex.
JobInfo.Builder setPersisted(boolean isPersisted)Set whether or not to persist this job across device reboots.
JobInfo.Builder setPrefetch(boolean prefetch)Setting this to true indicates that this job is designed to prefetch content that will make a material improvement to the experience of the specific user of this device.
JobInfo.Builder setRequiredNetwork(NetworkRequest networkRequest)Set detailed description of the kind of network your job requires.
JobInfo.Builder setRequiredNetworkType(int networkType)Set basic description of the kind of network your job requires.
JobInfo.Builder setRequiresBatteryNotLow(boolean batteryNotLow)Specify that to run this job, the device's battery level must not be low.
JobInfo.Builder setRequiresCharging(boolean requiresCharging)Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices).
JobInfo.Builder setRequiresDeviceIdle(boolean requiresDeviceIdle)When set true, ensure that this job will not run if the device is in active use.
JobInfo.Builder setRequiresStorageNotLow(boolean storageNotLow)Specify that to run this job, the device's available storage must not be low.
JobInfo.Builder setTransientExtras(Bundle extras)Set optional transient extras.
JobInfo.Builder setTriggerContentMaxDelay(long durationMs)Set the maximum total delay (in milliseconds) that is allowed from the first time a content change is detected until the job is scheduled.
JobInfo.Builder setTriggerContentUpdateDelay(long durationMs)Set the delay (in milliseconds) from when a content change is detected until the job is scheduled.
JobInfo.Builder 通过多个set方法设置的属性,最终 通过build()方法创建了JobInfo实例。之前创建的属性可以通过JobInfo的get方法获取到。
1) setPersisted(boolean isPersisted)方法不仅可以设置重启设备后该作业仍然生效,而且在android8.0以下的设备中这是一个很好的保活手段,即使在设置中强行停止了应用,只要激活条件到了该作业仍然会启动从而达到唤醒应用的目的。
2) setMinimumLatency(long minLatencyMillis):这个即经过minLatencyMillis时间再开始执行任务,此方法不能和setPeriodic(long time)同时使用,否则会引起异常。
3)setOverrideDeadline(long maxExecutionDelayMillis):设置最长等待时间,即使其他条件未满足,经过maxExecutionDelayMillis后任务都会执行。此方法不能和setPeriodic(long time)同时使用,否则会引起异常。
4)setRequiredNetworkType,setRequiresCharging和setRequiresDeviceIdle可能引起任务永远无法执行,除非设置了setOverrideDeadline,即使其他条件未满足,当最长等待时间到达时都会执行任务。
下面是一个简单作业的构建代码
JobScheduler scheduler =context.getSystemService(JobScheduler.class);
ComponentName mServieComponent = new ComponentName(context, MyJobService.class);
JobInfo jobInfo = new JobInfo.Builder(jobId, mServieComponent)
              .setMinimumLatency(miniTime)     //延时
        .setOverrideDeadline(deadLine)   //若失效,定时
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)   //任意网络
        .setPersisted(true) //android8.0以下清除数据以及设置中强制停止应用也可以自动起来
        .build();
scheduler.schedule(jobInfo);
三、JobService
JobService用来执行 JobScheduler设置的作业, JobService默认是在主线程执行,因此需要在onStartJob()中手动创建  thread/handler/ AsyncTask 去执行耗时任务。
JobService必须在manifest文件中声明 BIND_JOB_SERVICE 权限
<service android:name = "MyJobService"
              android:permission = "android.permission.BIND_JOB_SERVICE" >

JobService主要方法如下,其中 onStartJob和onStopJob必须实现。
Public methods
final void jobFinished(JobParameters params, boolean wantsReschedule)Call this to inform the JobScheduler that the job has finished its work.
abstract boolean onStartJob(JobParameters params)Called to indicate that the job has begun executing.
abstract boolean onStopJob(JobParameters params)This method is called if the system has determined that you must stop execution of your job even before you've had a chance to call jobFinished(JobParameters, boolean).
1、onStartJob(JobParameters params)
开始执行作业任务时触发onStartJob方法,在该方法里面执行具体任务,params可以获取到之前构建 JobInfo 时设置的一些参数。
onStartJob方法 返回一个boolean值。假设返回值是false,系统就认为任务已经运行完成,后面的 onStopJob方法将不再执行 。假设返回值是true,那么系统假定这个任务正要被运行,此时可能就需要开启新的线程来异步执行任务,当任务运行完成时你须要调用jobFinished(JobParameters params, boolean needsRescheduled)来通知系统,此时调用JobScheduler的cancel或者cancelAll方法则onStopJob会执行。
2、 jobFinished(JobParameters params, boolean wantsReschedule)
任务完成时手动调用jobFinished来通知JobManager,系统释放wakelock,所以当jobFinished执行后onStopJob方法就不再执行。 jobFinished方法可以在任意线程调用,因为它最终将在应用程序的主线程上运行。
JobParameters是通过onStartJob(JobParameters params)传给JobService的;另外一个布尔值needsRescheduled是告诉系统此任务是否需要进行重新调度,这取决于任务本身需求。
3、 onStopJob
当你主动通知任务执行完毕(jobFinished)之前,系统可能会要求你停止任务,这时将会调用onStopJob方法 。
当该任务的需求不再满足时或者通过cancel、cancelAll取消任务时将发生这种状况,系统可能会将你的wakelock释放。
返回true表示你希望对该任务重新进行调度,同样需要遵守退避策略;返回false表示你希望放弃该任务。


猜你喜欢

转载自blog.csdn.net/u013795543/article/details/80861953