在Oreo及以上版本中,需要使用JobScheduler来替代AlarmManager。以下是一个示例代码,用于在Oreo及以上版本上定期调用代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
JobScheduler jobScheduler =
(JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
ComponentName componentName =
new ComponentName(getApplicationContext(), YourJobService.class);
JobInfo jobInfo = new JobInfo.Builder(1, componentName)
.setPeriodic(86400000)
.build();
jobScheduler.schedule(jobInfo);
} else {
AlarmManager alarmManager =
(AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), YourReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(getApplicationContext(),
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 1000, 86400000, pendingIntent);
}
在此示例中,如果运行设备的API级别为Oreo或更高,则会调用JobScheduler以定期调用YourJobService类。否则,将继续使用AlarmManager以相同的方式调用YourReceiver类。