Search code examples
c#androidxamarinalarmmanager

How to set alarm using DateTime object for specific date and time in xamarin android?


i am working with alarm manager in android xamarin,and i have a date-time object, i want to set an alarm for that specific date-time. currently i am using following code to set alarm for same days minutes.

          alarmIntent.PutExtra("title", reminder.Title);
          alarmIntent.PutExtra("description", reminder.Description);
          int _id = reminder.ID;
          PendingIntent pendingIntent = PendingIntent.GetBroadcast(Activity, _id, alarmIntent, PendingIntentFlags.UpdateCurrent);
          AlarmManager alarmManager = (AlarmManager)Activity.GetSystemService(Context.AlarmService);
          DateTime dt = DateTime.ParseExact(reminder.ReminderTime, "yyyy.MM.dd HH:mm", CultureInfo.InvariantCulture);

          var totalMinutes = dt.Minute - DateTime.Now.Minute;
          var time = (totalMinutes * 60) * 1000;
          alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + time, pendingIntent);```

above code is working fine i just want to set alarm on a specific time.

Solution

  • DateTime dt= //some date
    DateTimeOffset dateOffsetValue = DateTimeOffset.Parse(dt.ToString());
                    var millisec = dateOffsetValue.ToUnixTimeMilliseconds();
    
                    alarmManager.Set(AlarmType.RtcWakeup, millisec, pendingIntent);
    

    above code resolved my issue