Xamarin Android Alarm Manager Issue

Xamarin Android Alarm Manager Issue

You are setting the time to trigger the alarm in the past by only using the timespan of 10 minutes, the number of milliseconds needs to be calculated from the beginning of the year 1970.

If the stated trigger time is in the past, the alarm will be triggered immediately.

Get the current time, and add time to it.

var TenMinsFromNow = Calendar.GetInstance(Android.Icu.Util.TimeZone.Default).TimeInMillis + TimeSpan.FromMinutes(10).TotalMilliseconds);

Current time in milliseconds from "1970-01-01T00:00:00Z":

 Java.Lang.JavaSystem.CurrentTimeMillis();

Or:

 Calendar.GetInstance(Android.Icu.Util.TimeZone.Default).TimeInMillis;

Xamarin AlarmManager Android

The problem is that your BroadcastReceiver does not have the [BroadcastReceiver] attribute.

This code works:

AlarmReceiver.cs

[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");

var resultIntent = new Intent(context, typeof(MainActivity));
resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);

var pending = PendingIntent.GetActivity(context, 0,
resultIntent,
PendingIntentFlags.CancelCurrent);

var builder =
new Notification.Builder(context)
.SetContentTitle(title)
.SetContentText(message)
.SetSmallIcon(Resource.Drawable.Icon)
.SetDefaults(NotificationDefaults.All);

builder.SetContentIntent(pending);

var notification = builder.Build();

var manager = NotificationManager.FromContext(context);
manager.Notify(1337, notification);
}
}

MainActivity.cs

[Activity(Label = "App3", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

SetContentView(Resource.Layout.Main);

var button = FindViewById<Button>(Resource.Id.MyButton);

button.Click += delegate
{
var alarmIntent = new Intent(this, typeof(AlarmReceiver));
alarmIntent.PutExtra("title", "Hello");
alarmIntent.PutExtra("message", "World!");

var pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);

var alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();
alarmManager.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 5*1000, pending);
};
}
}


Related Topics



Leave a reply



Submit