JobIntentService与IntentService的区别

JobIntentService与IntentService都是可以用来执行后台任务,在Android O之前,使用起来效果没多大差别,但是Android O以后JobIntentService不会立即执行,等手机进入一定状态后才会执行任务,所以不能用来执行及时的后台任务。

When running as a pre-O service, the act of enqueueing work will generally start the service immediately, regardless of whether the device is dozing or in other conditions. When running as a Job, it will be subject to standard JobScheduler policies for a Job with a setOverrideDeadline(long) of 0: the job will not run while the device is dozing, it may get delayed more than a service if the device is under strong memory pressure with lots of demand to run jobs.

the job will not run while the device is dozing 重点是这里的说明。
关于Doze模式的介绍,请参考:
Android中的Doze模式

参考JobIntentService的部分代码:

    @RequiresApi(26)
    static final class JobWorkEnqueuer extends JobIntentService.WorkEnqueuer {
        private final JobInfo mJobInfo;
        private final JobScheduler mJobScheduler;

        JobWorkEnqueuer(Context context, ComponentName cn, int jobId) {
            super(cn);
            ensureJobId(jobId);
            JobInfo.Builder b = new JobInfo.Builder(jobId, mComponentName);
            mJobInfo = b.setOverrideDeadline(0).build();
            mJobScheduler = (JobScheduler) context.getApplicationContext().getSystemService(
                    Context.JOB_SCHEDULER_SERVICE);
        }

        @Override
        void enqueueWork(Intent work) {
            if (DEBUG) Log.d(TAG, "Enqueueing work: " + work);
            mJobScheduler.enqueue(mJobInfo, new JobWorkItem(work));
        }
    }

mJobInfo = b.setOverrideDeadline(0).build();

JobIntentService本质上是通过JobScheduler来执行相关任务的,因此它的重点再JobScheduler。(后续补充)

关于JobScheduler,这个大神写的很详细,很好,就不重复去分析了:
Android 9.0 JobScheduler(二) JobScheduler框架结构简述及JobSchedulerService的启动
Android 9.0 JobScheduler(三) 从Job的创建到执行

你可能感兴趣的:(Android,android)