简体   繁体   English

Android AlarmManager 在错误的时间开始响铃

[英]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 在错误的时间触发

AlarmManager running at the wrong time AlarmManager 在错误的时间运行

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来自 AlarmManager 文档

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.使用未来日期时,获取该日期和时间的日历,然后设置闹钟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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