Search code examples
androidxamarinalarmmanager

Alarm Manager is sometimes very long to run the intent


I got a problem with the AlarmManager. When the alarm is set, if the alarm's hour has already passed the intent is started which is great. But sometimes there is a very long time (from 30 secondes to 3 minutes) before the intent is started. If anyone knows why, I'm curious to understand.

Here is my code :

 public static void setAlarm()
        {
            Intent intent = new Intent(Application.Context, typeof(AlarmReceiver));
            intent.SetAction("ExchangeGo");
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, intent, PendingIntentFlags.CancelCurrent);
            Calendar dayCalendar = Calendar.GetInstance(Java.Util.TimeZone.Default);
            dayCalendar.Set(CalendarField.HourOfDay, 8);
            dayCalendar.Set(CalendarField.Minute, 30);
            dayCalendar.Set(CalendarField.Second, 0);
            dayCalendar.Set(CalendarField.Millisecond, 0);       
            AlarmManager alarm = Application.Context.GetSystemService(Context.AlarmService).JavaCast<AlarmManager>();
            alarm.Cancel(pendingIntent);
            alarm.SetRepeating(AlarmType.RtcWakeup, dayCalendar.TimeInMillis, AlarmManager.IntervalDay, pendingIntent);

        }

And here the intent :

   [BroadcastReceiver]
    public class AlarmReceiver : BroadcastReceiver
    {
        private  String SOMEACTION = "ExchangeGo";
        public override void OnReceive(Context context, Intent intent)
        {
            String action = intent.Action;
            if (SOMEACTION.Equals(action))
            { 
                Intent intentService = new Intent(context, typeof(ExchangeService2));
                context.StartService(intentService);
            }
        }
    }

There is no problem with manifest cause it works, just a bit too long sometimes. And the problem is not from my second intent because I put a breakPoint just before and the waiting time is before the break point.

Anyone ?

Thanks for reading me.


Solution

  • As setRepeating() doesn't guarantee that it will happen at precise time. That's why you are getting delay of 30 secondes to 3 minutes.

    Replace setRepeating() with setExact() refer documentation from Here

    manager.setExact(AlarmManager.RTC, startTime.getTimeInMillis(), operation);
    

    To repeat this what you can do is, to schedule this alarm again after executing your current event. So when your 1st intent gets executed schedule alarm for 2nd event using setExact() only. This will guarantee the time accuracy you are expecting