简体   繁体   中英

Android AlarmManager starts ringing on wrong time

I am trying to create an alarm application. I am getting the alarm time settings from the user using a time picker

I have studied the following comments but could not find a solution:

Alarm starts at the wrong time

AlarmManager fire at the wrong time

AlarmManager running at the wrong time

When I set the alarm time before the current time, it starts ringing immediately. However, if the alarm time is set after the current time, it works fine.

Following is my code...

calendar.set(
             calendar.get(Calendar.YEAR),
                   calendar.get(Calendar.MONTH),
                   calendar.get(Calendar.DAY_OF_MONTH),
                   timePicker.getHour(),
                   timePicker.getMinute(),
                   0
           );
       AlarmManager alarmManager= (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent=new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
    alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);

If the user sets the alarm after the current time, it works fine. However, if the time is set before the current time (for the upcoming day), the ring immediately starts.

Kindly help me resolve this. Thanks in advance!

From AlarmManager docs

If the stated trigger time is in the past, the alarm will be triggered immediately.

Your calendar is set to current day and hence the alarm is going off immediately when the time is set to before the current time. When using future dates get the calendar for that date and time and then set the alarm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM