Xamarin Android 警报管理器问题 [英] Xamarin Android Alarm Manager Issue

查看:44
本文介绍了Xamarin Android 警报管理器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Xamarin Android 应用中有一个 AlarmManager.我正在使用 SetExact() 配置它,时间为 5 分钟.但它仅在五秒钟后就开始了.而且无论我什么时候配置它,它都会在 5 秒后触发.我在 Java 中使用了完全相同的代码,并且运行良好.

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.

代码:

[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.");
        }
    }

我如何使用 AlarmReceiver:

AlarmReceiver.Start(Activity,(long)TimeSpan.FromMinutes(10).TotalMilliseconds)

输出窗口:

14:14:20.217 5393-5393/AlarmReceiver: 开始,600000 后跳动毫秒.14:14:25.218 5393-5393/AlarmReceiver:触发

14:14:20.217 5393-5393/AlarmReceiver: Started, tigger after 600000 miliseconds. 14:14:25.218 5393-5393/AlarmReceiver: Triggered

推荐答案

你在过去设置触发报警的时间只用10分钟的时间跨度,毫秒数需要从开始计算1970 年.

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);

从1970-01-01T00:00:00Z"开始的以毫秒为单位的当前时间:

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

 Java.Lang.JavaSystem.CurrentTimeMillis();

或者:

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

这篇关于Xamarin Android 警报管理器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆