xamarin forms alarm manager code example

Example 1: xamarin forms alarm

public string Create(string title, string message, DateTime scheduleDate, Dictionary<string, string> extraInfo)
 {
 // Create the unique identifier for this notifications.
 var notificationId = Guid.NewGuid().ToString();
 
 
 // Create the alarm intent to be called when the alarm triggers. Make sure
 // to add the id so we can find it later if the user wants to update or
 // cancel.
 var alarmIntent = new Intent(Application.Context, typeof(NotificationAlarmHandler));
 alarmIntent.SetAction(BuildActionName(notificationId));
 alarmIntent.PutExtra(TitleExtrasKey, title);
 alarmIntent.PutExtra(MessageExtrasKey, message);
 
 
 // Add the alarm intent to the pending intent.
 var pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
 
 
 // Figure out the alaram in milliseconds.
 var utcTime = TimeZoneInfo.ConvertTimeToUtc(scheduleDate);
 var epochDif = (new DateTime(1970, 1, 1) - DateTime.MinValue).TotalSeconds;
 var notifyTimeInInMilliseconds = utcTime.AddSeconds(-epochDif).Ticks / 10000;
 
 
 // Set the notification.
 var alarmManager = Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;
 alarmManager?.Set(AlarmType.RtcWakeup, notifyTimeInInMilliseconds, pendingIntent);
 
 // All done.
 return notificationId;
 }

Example 2: xamarin forms alarm

[BroadcastReceiver]
internal class NotificationAlarmHandler : BroadcastReceiver
{
  public override void OnReceive(Context context, Intent intent)
  {
    // Pull out the parameters from the alarm.
    var message = intent.GetStringExtra("message");
    var title = intent.GetStringExtra("title");
 
    // Create the notification.
    var builder = new NotificationCompat.Builder(Application.Context)
     .SetContentTitle(title)
     .SetContentText(message)
     .SetSmallIcon(Resource.Drawable.logo_square_22x22)
     .SetAutoCancel(true);
 
 
    // Set this application to open when the notification is clicked. If the application
    // is already open it will reuse the same activity.
    var resultIntent = Application.Context.PackageManager.GetLaunchIntentForPackage(Application.Context.PackageName);
    resultIntent.SetAction(intent.Action);
    resultIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
 
    var resultPendingIntent = PendingIntent.GetActivity(Application.Context, 0, resultIntent, PendingIntentFlags.UpdateCurrent);
    builder.SetContentIntent(resultPendingIntent);
 
    // Show the notification.
    var notificationManager = NotificationManagerCompat.From(Application.Context);
    notificationManager.Notify(0, builder.Build());
  }
}