【问题标题】:Android AlarmManager starts ringing on wrong timeAndroid AlarmManager 在错误的时间开始响铃
【发布时间】:2019-10-17 18:19:17
【问题描述】:

我正在尝试创建一个警报应用程序。我正在使用时间选择器

从用户那里获取闹钟时间设置

我研究了以下cmets,但找不到解决方案:

Alarm starts at the wrong time

AlarmManager fire at the wrong time

AlarmManager running at the wrong time

当我将闹钟时间设置在当前时间之前时,它会立即开始响铃。但是,如果闹钟时间设置在当前时间之后,则可以正常工作。

以下是我的代码...

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

如果用户在当前时间之后设置了闹钟,它可以正常工作。但是,如果时间设置在当前时间(即将到来的一天)之前,则响铃会立即开始。

请帮我解决这个问题。提前致谢!

【问题讨论】:

    标签: android broadcastreceiver alarmmanager


    【解决方案1】:

    来自 AlarmManager 文档

    如果规定的触发时间已经过去,则立即触发警报。

    您的日历设置为当前日期,因此当时间设置为当前时间之前,闹钟会立即响起。使用未来日期时,获取该日期和时间的日历,然后设置闹钟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      相关资源
      最近更新 更多