【问题标题】:Why AlarmManager doesn't exactly repeating on device?为什么 AlarmManager 不能在设备上完全重复?
【发布时间】:2017-03-19 10:42:54
【问题描述】:

为什么 AlarmManager 有时会在 5 分钟后执行失败,这是应该的?例如,有一次它可能不起作用,但在下一个周期它会工作 2 次(或 3 次)。甚至滞后 1 分钟。

API 17 (Android 4.2.1) - setRepeating 应该是准确的。

public void scheduleAlarm()
    {
        Intent intent = new Intent(getApplicationContext(), TestAlarmReceiver.class);
        final PendingIntent pIntent = PendingIntent.getBroadcast(this, TestAlarmReceiver.REQUEST_CODE,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        long firstMillis = System.currentTimeMillis();
        AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 5 * 60 * 1000, pIntent); // every 5 minutes

        Log.i(TAG_LOG, "The alarm started");
    }

日志:

<...>
17.03.2017 07:20:30
17.03.2017 07:25:30
17.03.2017 07:30:30
17.03.2017 07:40:25  <- this
17.03.2017 07:40:30  <- this
17.03.2017 07:45:30
17.03.2017 07:50:30
17.03.2017 07:55:30
17.03.2017 08:00:30
17.03.2017 08:10:25  <- this
17.03.2017 08:10:30  <- this
17.03.2017 08:15:30
17.03.2017 08:20:30
<...>
17.03.2017 16:50:30
17.03.2017 16:55:30
17.03.2017 17:01:10  <- this
17.03.2017 17:05:30
17.03.2017 17:10:30
17.03.2017 17:15:30
17.03.2017 17:21:08  <- this
17.03.2017 17:25:30
17.03.2017 17:40:29  <- this
17.03.2017 17:40:29  <- this
17.03.2017 17:40:30  <- this
17.03.2017 17:45:30
17.03.2017 17:51:09  <- this
17.03.2017 17:55:30
17.03.2017 18:00:50
<...>

【问题讨论】:

    标签: android alarmmanager repeatingalarm


    【解决方案1】:

    setRepeating() 不应该按照你想要的方式工作。

    setExact()在准确的时间触发警报,但由于没有setExactRepeating()方法,需要使用setExact(),在BroadcastReceiver中,再次调用setExact()函数。

    没有简单的方法可以做到这一点,因为 Google 试图向您指出这对电池有害。如上所述使用setExact() 是您进行精确重复的唯一选择。

    【讨论】:

    • 是的,但我提到我有 API 17。上面没有setExact()
    猜你喜欢
    • 2019-06-08
    • 2016-04-10
    • 1970-01-01
    • 2021-11-16
    • 2020-12-03
    • 2023-03-28
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多