您可以使用以下方法设置闹钟:
/**
* Set the Alarm
*
* @param context the activity context
* @param id the alarm ID for this app
* @param hour the alarm hour
* @param minute the alarm minute
* @param timeZone the timezone "am" = Calendar.AM or "pm" = Calendar.PM
*/
public static void setAlarm(Context context, int id, int hour, int minute, String timeZone) {
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
AlarmStateCache cache = AlarmStateCache.getInstance(context);
cache.saveState(State.ON);
Calendar now = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, to24Hour(hour, timeZone));
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
if(calendar.before(now))
calendar.add(Calendar.DAY_OF_MONTH,1);
Intent intent = new Intent(context, YourReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(context, id, intent, 0);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 20, pIntent);
}
和辅助方法
public static int to24Hour(int hour, String zone) {
if (1 > hour && hour < 12)
throw new IllegalArgumentException("Hour must only be 1 - 12!");
return zone.equals("am") ? hour : hour + 12;
}
在setAlarm
方法中我们可以看到如果我们当前的时间已经过去,我们会增加 1 天,因此我们可以确保时间会在第二天左右提示。