Xamarin Android警报管理器问题

编程入门 行业动态 更新时间:2024-10-22 16:42:01
本文介绍了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.

获取当前时间,并

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

发布评论

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

>www.elefans.com

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