Android 13 确实存在设置精确闹钟的问题。在这个环境下,闹钟可能会在指定时间的几分钟内响起,而不是在确切的时间点。以下是一个可能的解决方案,可以通过将精确闹钟设置为 {@link AlarmManager.RTC_WAKEUP} 来解决这个
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyAlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at exactly 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
// Use RTC_WAKEUP to make sure the alarm rings at the exact time
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
} else {
alarmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
这个解决方案中有两个方面需要注意。第一个是将闹钟设置为 AlarmManager.RTC_WAKEUP
,这样系统将会唤醒设备以确保闹钟在指定的确切时间响起。第二个是在 Android M 以上的版本中,使用了新 API setExactAndAllowWhileIdle
,以确保闹钟在低功耗模式下也能被触发。