开发者

set the time in Alarm manager Android - alarm fired instantly

Here i am trying to set the alarm by using AlarmManger class. It is working fine with me but when i set the alarm time after Hours or mins from time picker,It will start the instantly when i save that alarm. the alarm. I need to alarm go off until i set the time. Below is my code is working but starts the alarm immediately when i save.

I am setting time only with the time picker.

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH,mHour,mMinute);
PendingIntent sender = PendingIntent.getBroadcast(AddAlarm.this, REQUEST_CODE, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

If i take below code alarm is not working..

 Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, mHour);
calendar.set(Calendar.MINUTE, mMinute);
PendingIntent sender = Pen开发者_如何学CdingIntent.getBroadcast(AddAlarm.this, REQUEST_CODE, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

Help me should i change in the to work properly.Thanks in advance...


The second code should normally work for dated alarms.

Keep in mind: If you set the HOUR and MINUTE you set them for the current day eg HOUR = 1 and MINUTE = 30 means you set an alarm for 01:30 AM. If it is over, you might get the alarm right now.

When you like to create an alarm in the future with 1:30 to go, then use the calendar.add(..,..) method.


I'm not sure what you're trying to do with this line:

calendar.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH,mHour,mMinute);

but I'm pretty certain it doesn't do what you want. This will set the calendar to be the hour & minute you have chosen on the 5th of March of the year 1 AD. When you convert this to milliseconds, you'll get 0 out, because that's before the earliest date that can be represented in milliseconds.

You also have a different Calendar API related problem in this line:

calendar.set(Calendar.HOUR, mHour);

Here, your problem is that the Calendar.HOUR field refers to the hour in 12-hour notation, whereas your mHour is presumably using 24-hour notation (otherwise you'd also need an AM/PM field to hold a full day's worth of times). You want Calendar.HOUR_OF_DAY instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜