3

我正在使用警报管理器在特定时间分配警报。我遇到了一个问题,如果我将时间设置得早于当前系统时间,那么警报动作将立即触发。如何防止这种行为?谢谢

我的代码:

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent serviceIntent = new Intent(context,AlarmService.class);
    PendingIntent pendingIntent = PendingIntent.getService(context.getApplicationContext(), 234324243, serviceIntent, 0);

/*sample of setting eariler time
timeAlarm.set(Calendar.YEAR, 2013);
timeAlarm.set(Calendar.MONTH, 10);
timeAlarm.set(Calendar.DAY_OF_MONTH, 13);
timeAlarm.set(Calendar.HOUR_OF_DAY, 12);
timeAlarm.set(Calendar.MINUTE, 9);
timeAlarm.set(Calendar.SECOND, 0);
*/
alarmManager.set(AlarmManager.RTC_WAKEUP, timeAlarm.getTimeInMillis(), pendingIntent);
4

1 回答 1

7

这是因为android报警管理器就是这样设计的。如果时间比当前系统时间早 1 天或更长时间,您可以修改您的时间。像这样:

Calendar c = Calendar.getInstance();        
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, second);

if (c.getTimeInMillis() < System.currentTimeMillis()){
    c.add(Calendar.DAY_OF_MONTH, 1);
}
于 2013-11-13T07:04:18.783 回答