【问题标题】:Where/how should I start my AlarmManager to not execute everytime when my Fragement created?每次创建 Fragment 时,我应该在哪里/如何启动我的 AlarmManager 以不执行?
【发布时间】:2016-10-26 18:51:32
【问题描述】:

我想设置一个每 20 秒触发一次的通知。我在 Fragment 的 onCreate() 方法中设置了一个 AlarmReceiver:

        Intent alarmIntent = new Intent(getActivity(), IntentService.AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(getContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 20000, pendingIntent);

在我的 IntentService 类中,我有以下静态类:

  public static class AlarmReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            Intent send = new Intent(context, IntentService.class);
            context.startService(send);
       }
    }

我想在上面开始的那个 IntentService 类中创建我的通知。

AlarmManager 工作,每 20 秒执行一次,但每次创建 Fragment 时也会触发它。

我的问题是:每次创建 Fragment 时我应该在哪里/如何启动我的 AlarmManager 以不执行?

【问题讨论】:

  • 在启动警报之前使用这个: if (pendingIntent = null) { START ALARAM MANAGER }

标签: android notifications alarmmanager intentservice


【解决方案1】:

您不是告诉警报管理器在从现在起 20 秒内然后每 20 秒触发一次,而是现在然后每 20 秒触发一次。这就是为什么 Android 会立即发出警报 - 它会赶上过去的警报,并且“现在”是在代码完成后的几毫秒之后。您需要确保第一个预定的闹钟在未来。

所以你真正需要的是:

alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 20000, 20000, pendingIntent);

这告诉警报管理器在 20 秒内安排下一个警报,每 20 秒重复一次。

【讨论】:

  • 很高兴我能帮上忙——最近才遇到同样的问题 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-14
相关资源
最近更新 更多