I'm not able to get the AlarmManager
to work correctly with a Calendar
or GregorianCalendar
object.
Global.StartingTime
is a static DateTime
object in another class. It's hour property returns the time in 24-Hour clock format.
Attempt 1 - Using Calendar
- Result: Doesn't fire
public void SetAlarm()
{
if (Global.StartingTime == null || Global.StartingTime == DateTime.MinValue) return;
Calendar now = Calendar.GetInstance (Java.Util.TimeZone.Default);
Calendar alarmTime = Calendar.GetInstance (Java.Util.TimeZone.Default);
alarmTime.Set(CalendarField.HourOfDay, Global.StartingTime.Hour);
alarmTime.Set(CalendarField.HourOfDay, Global.StartingTime.Minute);
if (alarmTime.Before(now))
alarmTime.Add(CalendarField.DayOfMonth, 1);
AlarmManager am = (AlarmManager) _context.GetSystemService (Context.AlarmService);
Intent intent = new Intent(_context, typeof(MainReceiver));
intent.PutExtra (ALARM_ACTION, true);
PendingIntent pi = PendingIntent.GetBroadcast (_context, 0, intent, 0);
am.SetRepeating (AlarmType.ElapsedRealtimeWakeup, alarmTime.TimeInMillis, AlarmManager.IntervalDay, pi);
AlarmSet = true;
}
Attempt 2 - Using GregorianCalendar
- Result: Fires right away, not at the given hour and minute.
public void SetAlarm()
{
if (Global.StartingTime == null || Global.StartingTime == DateTime.MinValue) return;
GregorianCalendar now = new GregorianCalendar ();
now.TimeInMillis = SystemClock.ElapsedRealtime();
GregorianCalendar alarmTime = new GregorianCalendar ();
alarmTime.Add(CalendarField.DayOfYear, now.Get(CalendarField.DayOfYear));
alarmTime.Set(CalendarField.HourOfDay, Global.StartingTime.Hour);
alarmTime.Set(CalendarField.Minute, Global.StartingTime.Minute);
alarmTime.Set(CalendarField.Second, now.Get(CalendarField.Second));
alarmTime.Set(CalendarField.Millisecond, now.Get(CalendarField.Millisecond));
alarmTime.Set(CalendarField.Date, now.Get(CalendarField.Date));
alarmTime.Set(CalendarField.Month, now.Get(CalendarField.Month));
if (alarmTime.Before (now))
alarmTime.Add (CalendarField.DayOfYear, 1);
AlarmManager am = (AlarmManager) _context.GetSystemService (Context.AlarmService);
Intent intent = new Intent(_context, typeof(MainReceiver));
intent.PutExtra (ALARM_ACTION, true);
PendingIntent pi = PendingIntent.GetBroadcast (_context, 0, intent, 0);
am.SetRepeating (AlarmType.RtcWakeup, alarmTime.TimeInMillis, AlarmManager.IntervalDay, pi);
AlarmSet = true;
}
As usual, I've asked this on StackOverflow so answer where ever you feel like.