通过不同的 API 使用 AlarmManager

Using AlarmManager With Different APIs

根据我的理解,如果我希望使用 AlarmManager Class 创建一个精确的重复警报(无论设备是否处于空闲模式),我需要使用不同的方案,具体取决于Android 版本已安装。根据我的读数,我需要将 setRepeating 与 RTC_WAKEUP 一起用于 API 最多 18,将 setExact 与手动重新安排 RTC_WAKEUP 一起用于 19 到 22 之间的 API ,最后 setExactAndAllowWhileIdle 手动重新安排 API >= 到 23.

  1. 我应该如何处理所有情况?我是否应该验证 API 版本然后相应地对警报进行编程?

  2. 或者是否有我可以用于向后兼容的支持库,它适用于所有场景?

  3. 如果我需要使用上面的第一个选项,我该如何取消警报?我是否需要使用类似的方案,在其中我将验证所使用的 API 版本,并为取消执行不同的代码,对应于安装的 API?

How should I handle all cases? Should I verify the API version and then program the Alarm accordingly?

如果需要,您可以在 Android 的 19 之前版本上使用 set() 并保持所有版本的手动重新安排一致,而不是对某些版本使用手动重新安排而对其他版本使用自动安排.

另请注意,在 Android P 上,如果您的应用属于非活动应用待机状态,我预计甚至 setExactAndAllowWhileIdle() 也不准确。

Or is there a Support Library I could use for backward compatibility, which would work for all scenarios?

There is AlarmManagerCompat,它提供了 setExactAndAllowWhileIdle().

的向后兼容实现

how do I cancel the Alarms? Do I need to use a similar scheme, in which I would verify the API version used, and have different code executed for the cancellation, corresponding to the API installed?

由于您通过 PendingIntent 取消,如果您使用不同的 PendingIntent 结构,则只需要不同的取消逻辑。我的猜测是,您可以对所有场景使用相同的 PendingIntent,在这种情况下,您的 cancel() 逻辑对于所有场景都是相同的。