我的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警报管理器问题
发布评论