问题:我的警报管理器立即触发。
我查看了堆栈溢出上的其他示例,其中人们面临着同样的问题,但我似乎无法弄清楚为什么我的也遇到同样的问题。我在 timeToFire 参数中输入了较高的值,但仍然会立即触发。
public void StartAlarm(string title, string message,int id, DateTime timeToBroadcast)
{
var localIntent = new Intent(_context, typeof (NotificationManager));
localIntent.PutExtra("title", title);
localIntent.PutExtra("message", shortMessage);
localIntent.PutExtra("Id", id);
_mAlarmSender = PendingIntent.GetBroadcast(_context, id, localIntent, 0);
var am = (AlarmManager) _context.GetSystemService(Context.AlarmService);
long timeToFire = SystemClock.CurrentThreadTimeMillis() + 100*1000;
am.Set(AlarmType.RtcWakeup, timeToFire, _mAlarmSender);
}
这些是我为了寻找答案而回顾过的其他问题
AlarmManager Interval for Android
why does my alarm go off straight away? (android)
set the time in Alarm manager Android - alarm fired instantly
最佳答案
根据 Android 文档,AlarmType.RtcWakeup
[1] 要求时间相对于 UTC。我相信 SystemClock.CurrentThreadTimeMillis()[2] 是自线程启动以来经过的毫秒数。我想这就是导致 triggerAtMillis
值被视为过去的原因,并立即触发警报,因为该值非常低。
您真正想要的是使用标准的 System.currentTimeMillis()
[3] 方法。这将为您提供相对于 UTC 的当前时间,这正是 AlarmManager
所期望的。
顺便说一句:它的 C# 版本是 Java.Lang.JavaSystem.CurrentTimeMillis()
[1] http://developer.android.com/reference/android/app/AlarmManager.html#RTC_WAKEUP
public static final int RTC_WAKEUP
Alarm time in System.currentTimeMillis() (wall clock time in UTC), which will wake up the device when it goes off.
Constant Value: 0 (0x00000000)
[2] http://developer.android.com/reference/android/os/SystemClock.html#currentThreadTimeMillis()
public static long currentThreadTimeMillis ()
Returns milliseconds running in the current thread.
Returns elapsed milliseconds in the thread
[3] http://developer.android.com/reference/java/lang/System.html#currentTimeMillis()
public static long currentTimeMillis ()
Returns the current time in milliseconds since January 1, 1970 00:00:00.0 UTC.
This method always returns UTC times, regardless of the system's time zone. This is often called "Unix time" or "epoch time". Use a DateFormat instance to format this time for display to a human.
This method shouldn't be used for measuring timeouts or other elapsed time measurements, as changing the system time can affect the results. Use nanoTime() for that.
希望这有帮助。
关于xamarin - AlarmManager 立即触发广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24655126/