Android 5.0 JobScheduler简介以及在进程自
前提:5.0以上,守护进程自拉活的模式已经不可用。同时由于forceStopPackage会禁用Broadcast、Alarm,因此应用在5.0以上的自拉活成为一个需要面临的新课题。
目前发现了两种方法可以做到在5.0以上实现应用的自拉活:
NotificationListenerService:缺点:需要用户打开开关;优点:实时性好,应用被杀马上拉起。
JobScheduler:下文将分析JobScheduler的实现原理、使用方法和优缺点。
JobScheduler主要API介绍:
JobScheduler:API 21以上提供的系统服务接口,是系统服务JobSchedulerService的客户端代理
http://developer.android.com/reference/android/app/job/JobScheduler.html
http://developer.android.com/samples/JobScheduler/index.html
获取:context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

JobInfo:应用程序向JobSchedulerService发出任务请求的描述类,使用JobInfo.Builder构建。
http://developer.android.com/reference/android/app/job/JobInfo.html
http://developer.android.com/reference/android/app/job/JobInfo.Builder.html
JobInfo.Builder主要API
设置为开机启动的任务

设置任务执行周期

设置重试策略

JobScheduler对于应用自拉活的作用和方法:
通过JobScheduler将JobService注册到系统中,系统在条件满足时,主动bind到JobService,完成拉活。注册的信息不会因forceStop而被清除。
为了起到及时守护的效果,目前设置了周期为3秒:每3秒系统就会bind/unbind一次,为了防止JobService重新实例化,在App启动时,通过startService方法先拉起JobService,并使其STICKY。
优点:API21以上可用,测试6.0的Nexus 5x可用,与守护进程方式一起覆盖了4.0—6.0的机型。
缺点:受到Doze、系统休眠限制
Demo:https://github.com/ziruiwang/DefendService.git
JobScheduler在系统中的主要结构
