AlarmManager 未设置或在一定时间后未在 Marshmallow 上触发

AlarmManager not set or not firing on Marshmallow after certain time

直到 Android 5:

我已经成功地使用以下结构在我的一些应用程序中启动 AlarmManager
    Intent serviceIntent = new Intent(context, MyService.class);
    PendingIntent pi = PendingIntent.getService(context, alarmId, serviceIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    DateTime inMinutes = (new DateTime()).plusMinutes(60);


    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    am.set(AlarmManager.RTC_WAKEUP, inMinutes.getMillis(), pi);

但是自 Marshmallow 以来,AlarmManager 要么未设置,要么在空闲时间后不再触发。当前的 运行 闹钟似乎又响了一次,但之后不会设置新的闹钟。

我阅读了一些文档,很可能是关于 Marshmallow Doze 的。所以我实现了以下(并检查它实际上正在执行):

    Intent serviceIntent = new Intent(context, MyService.class);
    PendingIntent pi = PendingIntent.getService(context, alarmId, serviceIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    DateTime inMinutes = (new DateTime()).plusMinutes(minutes);


    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if(Build.VERSION.SDK_INT >= 23)
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, inMinutes.getMillis(), pi);
    else {
        if(Build.VERSION.SDK_INT >= 19) {
            am.setExact(AlarmManager.RTC_WAKEUP, inMinutes.getMillis(), pi);
        } else {
            am.set(AlarmManager.RTC_WAKEUP, inMinutes.getMillis(), pi);
        }
    }

它没有改变任何东西。

有没有一种可靠的方法可以在 Marshmallow 闲置一段时间后设置和触发警报?

当然可以试试:

       setAlarmClock(AlarmManager.AlarmClockInfo info, PendingIntent operation)

如果您设置闹钟,打瞌睡模式不会启动way.I 在控制台上对此进行了测试。

不要忘记 AlarmClock Info 与 setAlarmclock 有不同的 PendingIntent

更新

如果你想做一个简单的闹钟(不是闹钟)。

这必须有效

    setExactAndAllowWhileIdle(int type, long triggerAtMillis, PendingIntent operation)

但我现在知道它没有。所以我开始寻找 google 并找到了这个。一种将应用程序添加到打瞌睡白名单的可能方法。也许 setExactAndAllowWhileIdle 有效。

https://developer.android.com/training/monitoring-device-state/doze-standby.html?hl=es

Users can manually configure the whitelist in Settings > Battery > Battery Optimization. Alternatively, the system provides ways for apps to ask users to whitelist them.

An app can fire the ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS intent to take the user directly to the Battery Optimization, where they can add the app. An app holding the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission can trigger a system dialog to let the user add the app to the whitelist directly, without going to settings. The app fires a ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent to trigger the dialog. The user can manually remove apps from the whitelist as needed. Before asking the user to add your app to the whitelist, make sure the app matches the acceptable use cases for whitelisting.