xamarin - 日期时间上的 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);
}
解决方案
毫秒分量,表示为 0 到 999 之间的值。
所以alarmDate.Millisecond
不返回 0 因为它从未被设置,它返回 0 因为它被设置为零然后你创建了 DateTime 对象alarmDate = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 5, 29, 0, DateTimeKind.Local);
您将时间设置为上午 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);
推荐阅读
- ios - 在本地保存敏感数据的安全方法?
- javascript - 在 PriorityERP 上使用 :FORM_APP_NAME 变量
- reactjs - 使用 ref 更改组件背景 - 反应原生
- string - 在 XSLT 中拆分 url 字符串
- android - UsageStatsManager 没有为时间间隔提供适当的数据
- c# - 让 TcpClient 等到数据写入
- sql - 提取其他字段也匹配的重复值
- python - 迭代时无法修改 Pandas DataFrame
- c# - 如何在 UWP 中创建带有叠加层的视频?
- reactjs - 从 Create React App 弹出后高阶组件文件中的问题