开发者

why does my alarm go off straight away? (android)

Trying to set alarms for certain days of the week, but currently puzzled as to why this alarm is getting fired immediately, no matter what I pass in as hr and min... (I know the day of the week stuff is wrong, just haven't got to that yet!)

public void setReminder(int hr, int min, int day)
{
     Intent intent = new Intent(mContext, AlarmReceiver.class);

     PendingIntent sender = PendingIntent.getBroadcast(mContext, alarmId, intent,开发者_如何学JAVA PendingIntent.FLAG_UPDATE_CURRENT);

     Calendar calendar = Calendar.getInstance();
     calendar.set(Calendar.HOUR_OF_DAY, hr);
     calendar.set(Calendar.MINUTE, min);
     calendar.set(Calendar.SECOND, 0);
     calendar.setFirstDayOfWeek(Calendar.SUNDAY);
     calendar.set(Calendar.DAY_OF_WEEK, day);


     // set the alarm to repeat every week at the same time
     mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, sender);
}

any ideas?


If calendar calendar.before(Calendar.getInstance()) == true (it means your are setting alarm to start in the past, it will fire immediately.

In such situation you can do following:

long start = calendar.getTimeMillis();
if (calendar.before(Calender.getInstance()) {
     start += AlarmManager.INTERVAL_DAY * 7;
}
// set alarm with start time

From docs:

If the time occurs in the past, the alarm will be triggered immediately, with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜