1

I am setting local notifications to fire at specific time in Xamarin.Android application. It all works but the set time seems to be little off, set time comes from user input (with minute precision). When setting notifications further in the future (days later) the notification fired at the next minute than it should have.

Below is my current code to calculate time. calendarEvent.StartTime is a DateTime property.

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

I would like to know how to accurately calculate the time so that notifications would fire at the start of the minute they are supposed to. In the current code they fire in the middle of the minute or later.

erythblue
  • 13
  • 6

1 Answers1

0

If you really need precision try to use the SetExact() method of the alarm manager class.

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

And I don't know if it is relevant, but if you are using events for a calendar maybe you should use RTC, since AlarmType.RTC is based on the clock, whereas AlarmType.ElapsedRealTime is based on the time passed since the device was turned on.

Erick Santander
  • 311
  • 3
  • 17
  • thanks, will try that. Now my code is as follows: `manager.SetExact(AlarmType.Rtc, (long)(JavaSystem.CurrentTimeMillis() + span.TotalMilliseconds), pendingIntent);` . Do you think that the time is calculated correctly now? It worked in short timespan. My previous code seemed to delay greatly. – erythblue Feb 25 '19 at 16:11
  • You're welcome, It looks like it should work without a problem, but test it a few times just to be completely sure. – Erick Santander Feb 25 '19 at 16:58
  • If this answer has helped you, could you put it as the accepted answer? – Erick Santander Mar 04 '19 at 10:30
  • Sorry, sure. There seems to still be some delay in long distance alarms but maybe that's for a different question. Need to examine it more. – erythblue Mar 04 '19 at 11:05
  • I think that is normal, there is a problem with long running alarms not being accurate, I looked a bit into a solution, and found [this](https://stackoverflow.com/a/48639824/10430240). it might be of some use to you, good luck! – Erick Santander Mar 04 '19 at 12:29