首页 > 解决方案 > 日期时间上的 xamarin SetAlarm

问题描述

我希望设置警报,以便在警报触发时发送通知。我拥有的以下代码alarmDate.Millisecond返回 0(因为它从未设置过)。它应该返回正确的毫秒以使警报起作用-我认为UTC需要毫秒-但时间必须是英国的格林威治标准时间/夏令时。

代码:

    private void InitBroadcast()
    {
        // Build the intents
        var intent = new Intent(this, typeof(MyReceiver));
        var pendingIntent = PendingIntent.GetBroadcast(this, 0, intent, 0);

        var alarmManager = (AlarmManager)GetSystemService(AlarmService);

        // Build the dates
        var currentDate = DateTime.Now;
        var alarmDate = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 5, 29, 0, DateTimeKind.Local);


        // If the alarm time has already past, set the alarm date to tomorrow
        if (DateTime.Compare(currentDate, alarmDate) < 0) {
            alarmDate.AddDays(1);
        }



        alarmManager.SetRepeating(AlarmType.RtcWakeup, alarmDate.Millisecond, millisInADay, pendingIntent);

        textView.SetText(string.Format("Alarm set for {0}", alarmDate.ToString()), TextView.BufferType.Normal);
    }

标签: xamarinxamarin.android

解决方案


检查文档:https ://docs.microsoft.com/en-us/dotnet/api/system.datetime.millisecond?view=netframework-4.7.2#System_DateTime_Millisecond

毫秒分量,表示为 0 到 999 之间的值。

所以alarmDate.Millisecond不返回 0 因为它从未被设置,它返回 0 因为它被设置为零然后你创建了 DateTime 对象alarmDate = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 5, 29, 0, DateTimeKind.Local);

请参阅:https ://docs.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.7.2#System_DateTime__ctor_System_Int32_System_Int32_System_Int32_System_Int32_System_Int32_System_Int32_System_DateTimeKind_

您将时间设置为上午 5:29 的当前日期(秒数为 0,因此暗示了毫秒数为 0)。

alarmDate.Ticks将为您提供自 21 世纪初以来经过的“滴答声”数量(1/10,000 毫秒)。但请记住 SushiHangover 在他的评论中的 so 链接中所说的话

Android 的 AlarmManager 基于 Android/Linux Epoch 毫秒

不是 .NET DateTime 滴答声。纪元毫秒是自 1970 年 1 月 1 日 00:00:00 GMT (1970-01-01 00:00:00 GMT) 以来经过的毫秒数。

因此,不要传递alarmDate.Millisecond给该alarmManager.SetRepeating方法,而是使用当前时间和格林威治标准时间 1970 年 1 月 1 日午夜之间的 TimeSpan 来获取纪元毫秒并将其传递,例如:

var epochMs = (alarmDate - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
alarmManager.SetRepeating(AlarmType.RtcWakeup, (Int64)epochMs, millisInADay, pendingIntent);

推荐阅读