如何为 Xamarin.Android AlarmManager 设置准确的时间

How to set accurate time for Xamarin.Android AlarmManager

我在 Xamarin.Android 应用程序中将本地通知设置为在特定时间触发。一切正常,但设置时间似乎有点偏差,设置时间来自用户输入(精确到分钟)。当在未来(几天后)进一步设置通知时,通知会在下一分钟触发,而不是它应该有的。

下面是我当前计算时间的代码。 calendarEvent.StartTime 是日期时间 属性。

TimeSpan span = calendarEvent.StartTime - DateTime.Now;
manager.Set(AlarmType.ElapsedRealtime,(long)(SystemClock.ElapsedRealtime() + span.TotalMilliseconds),pendingIntent);     

我想知道如何准确计算时间,以便通知会在它们应该的那一分钟开始时触发。在当前代码中,它们会在一分钟中间或更晚时间触发。

如果您确实需要精度,请尝试使用警报管理器的 SetExact() 方法 class。

TimeSpan span = calendarEvent.StartTime - DateTime.Now;
manager.SetExact(AlarmType.ElapsedRealtime,(long)(SystemClock.ElapsedRealtime() + span.TotalMilliseconds),pendingIntent);

而且我不知道它是否相关,但是如果您将事件用于日历,也许您应该使用 RTC,因为 AlarmType.RTC 基于时钟,而 AlarmType.ElapsedRealTime 是基于设备开启后经过的时间。