Xamarin Android Alarm Manager Issue

2019-01-15 20:00发布

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

1条回答
\"骚年 ilove
2楼-- · 2019-01-15 20:53

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;
查看更多
登录 后发表回答