在API 31及以上版本中,Android禁止了后台服务的自启动。我们可以通过使用“JobScheduler”来代替后台服务。示例代码如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent = new Intent(context, MyJobService.class);
intent.setAction("android.intent.action.RUN");
JobInfo info = new JobInfo.Builder(1, new ComponentName(context, MyJobService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE)
.setPersisted(true)
.setRequiresCharging(false)
.setBackoffCriteria(3000, JobInfo.BACKOFF_POLICY_LINEAR)
.setInterval(3000)
.setOverrideDeadline(3000)
.build();
JobScheduler scheduler = (JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
scheduler.schedule(info);
} else {
Intent intent = new Intent(context, MyBackgroudService.class);
intent.setAction("android.intent.action.RUN");
context.startForegroundService(intent);
}
以上代码中,我们首先判断当前API版本是否为31及以上。如果是,我们就使用“JobScheduler”来代替后台服务。否则,我们仍然使用原来的后台服务。需要注意的是,“JobScheduler”应该在主线程中调用,否则会报错。