Android闹钟立即启动

时间:2012-05-05 10:44:15

标签: android alarm

为什么警报会立即启动而不是指定时间?

Intent myIntent = new Intent(Notepad.this, MyAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getService(Notepad.this, 0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
         Calendar calendar = Calendar.getInstance();
         calendar.setTimeInMillis(System.currentTimeMillis());
         calendar.set(Calendar.YEAR, 2012);
         calendar.set(Calendar.MONTH, 4);
         calendar.set(Calendar.DAY_OF_MONTH, 5);
         calendar.set(Calendar.HOUR_OF_DAY, 10);
         calendar.set(Calendar.MINUTE, 30);
         calendar.set(Calendar.SECOND, 4);
     alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

如果我只使用calendar.add(Calendar.SECOND, 5);,它会在5秒后启动。

解决方案基于尼古拉斯的回答

        Date dat  = new Date();//initializes to now
        Calendar cal_alarm = Calendar.getInstance();
        Calendar cal_now = Calendar.getInstance();
        cal_now.setTime(dat);
        cal_alarm.setTime(dat);
        cal_alarm.set(Calendar.HOUR_OF_DAY,Integer.valueOf(h));
        cal_alarm.set(Calendar.MINUTE, Integer.valueOf(m));
        cal_alarm.set(Calendar.SECOND,0);

        if(cal_alarm.before(cal_now)){
            cal_alarm.add(Calendar.DATE,1);
        }

1 个答案:

答案 0 :(得分:1)

对我而言,您似乎将日历时间和日期设置为闹钟时间。也许设置两个不同的日历,其中一个用于当前时间,另一个用于闹钟时间。这有意义吗?