Android alarm sets off immediately

女生的网名这么多〃 提交于 2019-12-11 16:32:20

问题


Why does the alarm set off immediately instead of the specified time?

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);

If I use only calendar.add(Calendar.SECOND, 5);, it sets off after 5 seconds.

SOLUTION based on Nicholas' answer

        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:


To me it seems that you are setting the calendar time and day to the alarm time. Maybe set up two different calendars and have one for the current time and another for the alarm time. Does that make sense?



来源:https://stackoverflow.com/questions/10461083/android-alarm-sets-off-immediately

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!