AlarmManager 在 S5 Neo 的睡眠模式下无法正常工作

AlarmManager not working as expected in sleep mode on S5 Neo

我在每分钟触发一次的服务中使用 AlarmManager。

    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0,
            getUpdateServiceIntent(mContext), PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

    // Cancel any pending Intent
    am.cancel(pendingIntent);

    // Set a new one
    am.set(AlarmManager.RTC_WAKEUP, 60000, pendingIntent);

在三星 S5 Neo 上: 当屏幕处于活动状态时,它会按预期工作。 当屏幕关闭时,它每 5 分钟触发一次(而不是一次)。

我在 S5 Mini(Android 4.4)、Nexus 5 5.1 和 Nexus 5 6.0 上尝试了这个完全相同的代码,这个代码工作正常。

targetSdkVersion 是 19.

知道如何在屏幕关闭时保持 AlarmManager 正常工作吗? 延迟还是5分钟,就算我要求30秒

编辑: 我也尝试了 'setExact' 方法,但它没有改变任何东西。每次闹钟之间还有5分钟的间隔。

你可能应该使用

AlarmManager#setExact(int type, long triggerAtMillis, PendingIntent operation)

而不是

AlarmManager#set(int type, long triggerAtMillis, PendingIntent operation))

Take a look

来自 google :

AlarmManager#set(int type, long triggerAtMillis, PendingIntent operation))

Note: Beginning in API 19, the trigger time passed to this method is treated as inexact: the alarm will not be delivered before this time, but may be deferred and delivered some time later. The OS will use this policy in order to "batch" alarms together across the entire system, minimizing the number of times the device needs to "wake up" and minimizing battery use. In general, alarms scheduled in the near future will not be deferred as long as alarms scheduled far in the future.

编辑:

我在报警应用程序中使用的是什么:

清单:

<uses-permission android:name="android.permission.WAKE_LOCK"/>

Java代码:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(nextAlarm.getTimeInMillis(), pendingIntent);
  alarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
}else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
  alarmManager.setExact(android.app.AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), pendingIntent);
}else {
  alarmManager.set(android.app.AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), pendingIntent);
}