【问题标题】:How to prevent alarm from running the passed time on starting如何防止警报在启动时运行经过的时间
【发布时间】:2014-04-01 06:27:03
【问题描述】:

我有一个带有 RTC 警报的应用程序。目前,我将警报设置为每天上午 8:00 触发。我的问题是,当闹钟在(下午 4:00)开始时,它会考虑过去的开始时间(上午 8 点),因此会运行。

我希望闹钟仅在上午 8:00 左右运行,但如果在当天晚些时候启动,则不会运行。知道怎么做吗?

【问题讨论】:

    标签: android alarmmanager


    【解决方案1】:

    建议你使用calendar.add(Calendar.DAY_OF_YEAR, 1);

    学习以下代码:

    Calendar calendar = Calendar.getInstance();
    // 9 AM 
    calendar.add(Calendar.DAY_OF_YEAR, 1);   ///to avoid firing the alarm immediately
    calendar.set(Calendar.HOUR_OF_DAY, 9);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    PendingIntent pi = PendingIntent.getService(context, 0,
                new Intent(context, MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                                    AlarmManager.INTERVAL_DAY, pi);
    

    Original Source

    【讨论】:

    • 聪明的想法,但是你确定如果你写的代码在晚上 11:00 运行,它仍然会在明天早上 9:00 被调用吗?只是增加了 1 天给我的印象是会延迟 1 天
    • @MahmoudBadri 是的,我 100% 确定,我已经用那一行测试了这段代码。
    • 好的,我接受这个答案,因为它更容易,虽然 nikis 的答案更准确,但在我的情况下,我想要更容易
    【解决方案2】:

    您使用的是setInexactRepeatingsetRepeating,对吗?因此,要处理这种情况,只需比较 2 次:以毫秒为单位的当前时间和以毫秒为单位的(上午 8 点,当天)。如果第一次多于第二次,那么您应该在(次日上午 8 点)触发警报,如果不是 -(当天上午 8 点)。

    【讨论】:

      【解决方案3】:

      就我而言,如果时间还没有过去,我希望警报在当天触发,所以我需要稍微改进 Lucifer 的答案。

      void setTheAlarm(int hour, int minute)
      {
          SettingsData.TriggerTime triggerTime = common.settingsData.getDeviceParamInfo().getConnectionTime();
      
          Calendar calendar = Calendar.getInstance();
      
          calendar.set(Calendar.HOUR_OF_DAY, hour);
          calendar.set(Calendar.MINUTE, minute);
          calendar.set(Calendar.SECOND, 0);
      
      
          if(System.currentTimeMillis() > calendar.getTimeInMillis())
          {
              calendar.add(Calendar.DAY_OF_YEAR, 1);   ///to avoid firing the alarm immediately
          }
      
          // With setInexactRepeating(), you have to use one of the AlarmManager interval
          // constants--in this case, AlarmManager.INTERVAL_DAY.
          alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                  AlarmManager.INTERVAL_DAY, alarmIntent);
      
          Log.i("setTheAlarm", String.format("Alarm is set to %02d:%02d", hour, minute));
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 1970-01-01
        相关资源
        最近更新 更多