Xamarin Android 警报管理器问题

编程入门 行业动态 更新时间:2024-10-21 23:15:49
本文介绍了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 警报管理器问题

本文发布于:2023-11-27 03:41:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636430.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:管理器   警报   Xamarin   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!