在AndroidManifest.xml文件中添加以下代码,以请求SCHEDULE_EXACT_ALARM权限:
同时,在代码中,使用AlarmManager.setExactAndAllowWhileIdle()或AlarmManager.setAlarmClock()方法来设置闹钟。
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
// Set the alarm to repeat every day
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
这将允许您的应用在闹钟和提醒应用中显示,并设置准确的闹钟。注意,SCHEDULE_EXACT_ALARM权限只在API级别23及以上可用。如果您的应用需要兼容较低级别的API,则应使用AlarmManager.set()和AlarmManager.setRepeating()方法,而不是setExactAndAllowWhileIdle()或setAlarmClock()。