首页 > 解决方案 > 即使设备处于打盹模式,如何使重复警报工作

问题描述

我四处寻找,但没有找到解决方案。我的应用程序需要在用户决定的不同时间显示每日通知,但警报管理器无法正常工作,如果我将时间设置为接下来的几分钟,它将显示通知,但大多数时候当我不使用设备时它不起作用。这就是我一直试图设置的重复警报。

        Intent intent = new Intent(Reminder.this, AlarmReceiverDaily.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(Reminder.this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) Reminder.this.getSystemService(ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent);

即使我的设备处于打盹模式,如何通过以下代码设置重复警报?

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(targetCal.getTimeInMillis(),pendingIntent),pendingIntent);
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        alarmManager.setExact(AlarmManager.RTC, targetCal.getTimeInMillis(), pendingIntent);
    else
        alarmManager.set(AlarmManager.RTC, targetCal.getTimeInMillis(), pendingIntent);

如果我不能将 setAlarmClock() 与重复闹钟一起使用,那么您更喜欢使用哪种解决方案来制作重复闹钟并且它必须有效。

标签: androidalarmmanagerrepeatingalarmsetalarmclock

解决方案


你必须使用:

if( Build.VERSION.SDK_INT >= 23 ){
    alarmManager.setExactAndAllowWhileIdle( ... );
}

推荐阅读