在AndroidManifest.xml文件中将应用程序的目标API级别升级为31及以上,并添加以下代码示例:
if (Build.VERSION.SDK_INT >= 31) {
Intent alarmIntent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = getSystemService(AlarmManager.class);
AlarmManager.AlarmClockInfo alarmClockInfo =
new AlarmManager.AlarmClockInfo(System.currentTimeMillis() + 10000, pendingIntent);
alarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
} else {
Intent intent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if(Build.VERSION.SDK_INT>=23)
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pendingIntent);
else if(Build.VERSION.SDK_INT>=19)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pendingIntent);
else
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pendingIntent);
}
在代码示例中,我们使用了if语句,如果设备的API级别大于或等于31,则使用setAlarmClock()方法设置闹钟;否则,使用setExactAndAllowWhileIdle(),setExact()或set()方法设置闹钟。这样可以确保应用程序在Android 12上运行时能够正确地设置闹钟。