Setting Alarms on Android

Setting Alarms on Android

Setting alarms on Android is not straightforward. The sticky part is setting the time for an alarm using AlarmManager.

Instead of taking a DateTime field, AlarmManager takes a value of type “long” that represents the time, in milliseconds, to trigger the alarm.

What’s more there’s two types of times: an elapsed time and a “Real Time Clock (RTC)”. The elapsed time represents the number of milliseconds since boot time. RTC time is the actual time expressed as UTC time. As if that wasn’t enough wrinkles, the time AlarmManager refers to is from EPOCH (Unix).

So to convert a local DateTime member to AlarmManager milliseconds use the following code:

var tDiff = new DateTime(1970, 1, 1) - DateTime.MinValue;
var utcAlarmTimeInMillis = YourDateTimeMember.ToUniversalTime().AddSeconds(-tDiff.TotalSeconds).Ticks / 10000;

Then use it with AlarmManager:

var alarmManager = (AlarmManager) Application.Context.GetSystemService(Context.AlarmService);
// For KitKat and higher use SetExact for preserving battery life, 
// for previous versions use Set:
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
  alarmManager.SetExact(AlarmType.RtcWakeup, utcAlarmTimeInMillis, pIntent);
else
  alarmManager.Set(AlarmType.RtcWakeup, utcAlarmTimeInMillis, pIntent);

Special thanks to David Conlisk in the Xamarin forums.