I have an AlarmManager
in my Xamarin Android App. I'm configuring it using SetExact()
with the time of 5 minutes. But it is being started after only five seconds. And no matter what time i'm configuring it with, it will always trigger after 5 seconds.
I've used the exact same code in Java, and it worked perfectly fine.
The code:
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Log.Info("AlarmReceiver", "Triggered");
}
public static void Start(Context context, long triggerAfterMilis)
{
var type = AlarmType.RtcWakeup;
var alarmManager = (AlarmManager) context.GetSystemService(Context.AlarmService);
var timerIntent = PendingIntent.GetBroadcast(context, 0, new Intent(context, typeof(AlarmReceiver)), PendingIntentFlags.CancelCurrent);
alarmManager.Cancel(timerIntent);
if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
alarmManager.SetAndAllowWhileIdle(type, triggerAfterMilis, timerIntent);
else if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
alarmManager.SetExact(type, triggerAfterMilis, timerIntent);
else
alarmManager.Set(type, triggerAfterMilis, timerIntent);
Log.Info("AlarmReceiver", $"Started, tigger after {triggerAfterMilis} miliseconds.");
}
}
How I'm using the AlarmReceiver
:
AlarmReceiver.Start(Activity,(long)TimeSpan.FromMinutes(10).TotalMilliseconds)
The output window:
14:14:20.217 5393-5393/AlarmReceiver: Started, tigger after 600000 miliseconds. 14:14:25.218 5393-5393/AlarmReceiver: Triggered
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.
Get the current time, and add time to it.
Current time in milliseconds from "1970-01-01T00:00:00Z":
Or: