Stop AlarmManager if the time has passed

时间:2015-06-15 14:55:20

标签: android alarmmanager

The code is like this :

 public void start() {
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval = 5000;

    /* Set the alarm to start at 21:50*/
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 21);
    calendar.set(Calendar.MINUTE, 50);

    /* Repeating on every 5 seconds interval */
    manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            5000, pendingIntent);
}

So when the time has exactly 21:50, the alarm has started running. But i want to stop automatically if the time is 22:00.

How is it ?

1 个答案:

答案 0 :(得分:1)

A hack I could think of is giving Thread.sleep(10000*60) and then manager.cancel(pendingIntent) , thread sleep would pause start() execution for 10 minutes and cancel would remove the alarm as per documentation. This is just a work around because the alarm needs to be created once again. Also start() should be uninterrupted for next 10 minutes.

 public void start() {
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval = 5000;

    /* Set the alarm to start at 21:50*/
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 21);
    calendar.set(Calendar.MINUTE, 50);

    /* Repeating on every 5 seconds interval */
    manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            5000, pendingIntent);
    Thread.sleep(10000*60);
    manager.cancel(pendingIntent);

}