Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c# - Xamarin Android Alarm Manager Issue

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...