【问题标题】:Alarm Manager with 2 pending intents only 1 works?具有 2 个待处理意图的警报管理器只有 1 个有效?
【发布时间】:2016-05-31 21:21:31
【问题描述】:

我设置了 2 个闹钟,一个用于通知,另一个用于执行某些任务。我的问题是似乎只有一个警报有效(通知服务一个,第一个警报设置)。另一个警报永远不会响起。这是我的代码:

Intent myIntent1 = new Intent(getApplicationContext(), NotificationService.class);
        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, myIntent1, 0);
        AlarmManager alarmManager1 = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeInMillis(System.currentTimeMillis());
        long frequency1 = 30 * 1000; // in ms
        alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), frequency1, pendingIntent);

        // Set alarm to fire go to Next day everyday at the same time
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 14); // For 1 PM or 2 PM
        calendar.set(Calendar.MINUTE, 57);
        calendar.setTimeInMillis(System.currentTimeMillis());
        Intent myintent = new Intent(getApplicationContext(), AlarmNextDayService.class);
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getService(getApplicationContext(), 11, myintent,0 );
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pi);

欢迎提出任何建议。到目前为止,我也查看了其他资源,但对我来说没有任何用处。 我还在清单文件中添加了警报权限,如下所示:

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

谢谢

【问题讨论】:

  • 您是否尝试在每个意图上添加唯一标识符,例如:Intent intent = new Intent("uniqId", null, context, Receiver.class);
  • 清单中是否列出了第二个Service?另外,您是否意识到在设置小时和分钟后将Calendar 实例重置为当前时间?还要记住,在该时间间隔内,不准确的警报可能会关闭相当多的时间。
  • 原来是问题所在,@MikeM。你能把它写成答案吗?
  • 这很酷。简单的修复。如果您愿意,您可以发布答案,或者请已经发布的人修改他们的答案。不过谢谢。真高兴你做到了。干杯! (附注 - 您不需要 SET_ALARM 权限。)

标签: android alarmmanager


【解决方案1】:
Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 14); // For 1 PM or 2 PM
    calendar.set(Calendar.MINUTE, 57);
    calendar.setTimeInMillis(System.currentTimeMillis());

您正在设置 HOUR_OF_DAY 和 MINUTE,但您可以通过调用 setTimeInMillis(System.currentTimeMillis()); 来覆盖它们;

之后,您使用已经过去的 calendar.getTimeMillis() 值设置闹钟,所以我认为闹钟被取消了。

【讨论】:

    【解决方案2】:

    您很可能会遇到问题,因为由于省电,Service 不能保证在警报触发时运行。如果您的设备在警报响起时处于电池状态且处于空闲状态,则在下次设备充满电或使用交流电源时才会触发。您需要使用一个BroadcastReceiver,它持有一个唤醒锁,然后在完成后由Service 释放。 WakefulBroadcastReceiver 使这更容易处理。此article 将有助于提供更多详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多