Scheduling repeating alarms

Hello,
I want to show a local notification to the user every day on a predefined time. Android documentation has a sample code in this link (developer.android.com/training/scheduling/alarms.html#set) that can be used for scheduled repeating alarms. My code is:

var calendar = Calendar.Instance;
calendar.TimeZone = TimeZone.GetTimeZone("Europe/Stockholm");
calendar.Set(CalendarField.HourOfDay, 19);
calendar.Set(CalendarField.Minute, 15);

//BootReceiver is derived from BroadcastReceiver which registers the service on boot (Intent.ActionBootCompleted)
var alarmIntent = new Intent(Instance, typeof(BootReceiver));
var pendingIntent = PendingIntent.GetBroadcast(Instance,
    0,
    alarmIntent,
    PendingIntentFlags.UpdateCurrent);

var alarmManager = (AlarmManager)Instance.GetSystemService(Context.AlarmService);
alarmManager.SetInexactRepeating(AlarmType.RtcWakeup,
    calendar.TimeInMillis,
    AlarmManager.IntervalDay,
    pendingIntent);

This partly works, depending on the current system time:

  • If the system time is smaller than the given time, notification is being shown on the stated time.
  • If the system time is larger than the given time, a notification is being shown directly after the application start, but scheduled notification at the stated time works also.

I do not want to fire notifications after the app start, could anyone please help me with daily notification registering?

Best Answer

Answers

  • erdihuerdihu Member ✭✭

    Has anyone not experienced a similar issue before?

  • erdihuerdihu Member ✭✭

    Thanks, this seems to fix the problem.

  • erdihuerdihu Member ✭✭

    This is the full code if anyone needs it:

            private static void RegisterNotification(DateTime scheduleTime)
            {
                if (DateTime.Now > scheduleTime)
                {
                    scheduleTime = scheduleTime.AddDays(1);
                }
    
                var alarmIntent = new Intent(Instance, typeof(BootReceiver));
                var pendingIntent = PendingIntent.GetBroadcast(Instance,
                    0,
                    alarmIntent,
                    PendingIntentFlags.UpdateCurrent);
    
                var alarmManager = (AlarmManager)Instance.GetSystemService(Context.AlarmService);
    
                // For future reference: 
                // https://nftb.saturdaymp.com/today-i-learned-how-to-create-a-local-notification-in-xamarin-android/
                var utcTime = TimeZoneInfo.ConvertTimeToUtc(scheduleTime);
                var epochDif = (new DateTime(1970, 1, 1) - DateTime.MinValue).TotalSeconds;
                var notifyTimeInInMilliseconds = utcTime.AddSeconds(-epochDif).Ticks / 10000;
    
                alarmManager.SetInexactRepeating(AlarmType.RtcWakeup,
                    notifyTimeInInMilliseconds,
                    AlarmManager.IntervalDay,
                    pendingIntent);
            }
    
Sign In or Register to comment.