xamarin alarm app code example
Example 1: xamarin forms alarm
public string Create(string title, string message, DateTime scheduleDate, Dictionary<string, string> extraInfo)
{
var notificationId = Guid.NewGuid().ToString();
var alarmIntent = new Intent(Application.Context, typeof(NotificationAlarmHandler));
alarmIntent.SetAction(BuildActionName(notificationId));
alarmIntent.PutExtra(TitleExtrasKey, title);
alarmIntent.PutExtra(MessageExtrasKey, message);
var pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
var utcTime = TimeZoneInfo.ConvertTimeToUtc(scheduleDate);
var epochDif = (new DateTime(1970, 1, 1) - DateTime.MinValue).TotalSeconds;
var notifyTimeInInMilliseconds = utcTime.AddSeconds(-epochDif).Ticks / 10000;
var alarmManager = Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;
alarmManager?.Set(AlarmType.RtcWakeup, notifyTimeInInMilliseconds, pendingIntent);
return notificationId;
}
Example 2: xamarin forms alarm
[BroadcastReceiver]
internal class NotificationAlarmHandler : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");
var builder = new NotificationCompat.Builder(Application.Context)
.SetContentTitle(title)
.SetContentText(message)
.SetSmallIcon(Resource.Drawable.logo_square_22x22)
.SetAutoCancel(true);
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);
var notificationManager = NotificationManagerCompat.From(Application.Context);
notificationManager.Notify(0, builder.Build());
}
}