Android 当 phone 屏幕关闭时,AlarmManager 默认为 5 分钟

Android AlarmManager defaulting to 5 minutes when phone screen is off

所以我遇到了 AlarmManager 的问题。我正在尝试每 2 分钟 运行 一些代码,当 phone 处于唤醒状态时它可以正常工作,但当设备进入睡眠状态时则不行 - 在睡眠期间,间隔完全相隔 5 分钟。

由于我想要的间隔是 2 分钟,这大约比我的目标间隔低 250%,这对于我的特定应用来说是不可接受的。

我知道 API 19 中的变化,并已按照建议在我的 BroadcastReceiver 中使用 setExact() 重新安排警报。代码如下:

用于触发BroadcastReceiver的代码:

    Intent intent = new Intent(this, AlarmReceiver.class);
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(this,  0, intent, 0);

    mAlarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3000, pendingIntent);

这段代码在我的 BroadcastReceiver 中,它重新安排了警报:

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "AlarmService Triggered.", Toast.LENGTH_SHORT).show();
    Log.d(this.getClass().getSimpleName(), "Service triggered");

    Intent newIntent = new Intent(context, this.getClass());
    mPendingIntent = PendingIntent.getBroadcast(context, 0, newIntent, 0);

    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 120000, mPendingIntent);
}

有人对我如何解决这个问题有建议吗?非常令人沮丧的是,AlarmManager 完全无视我希望在准确时间触发警报的愿望。有没有其他方法可以让我按照自己的意愿以 2 分钟的间隔安排代码?

设备:三星 Galaxy S6,OS5.1.1

将 ELAPSED_REALTIME_WAKEUP 替换为 RTC_WAKEUP。

我是这样安排闹钟的:

        mTargetTime = System.currentTimeMillis() + timeout * 1000L;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mTargetTime, mPendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, mTargetTime, mPendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, mTargetTime, mPendingIntent);
        }

正如@Francesc 所建议的,它最终成为了三星设备。在另一个 phone 上试过,现在它完美无缺。

给你一个教训——不要买三星,他们做的东西很奇怪,哈哈。