xamarin - AlarmManager 立即触发广播

标签 xamarin xamarin.android

问题:我的警报管理器立即触发。

我查看了堆栈溢出上的其他示例,其中人们面临着同样的问题,但我似乎无法弄清楚为什么我的也遇到同样的问题。我在 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/

相关文章:

visual-studio - IDE0006 警告和许多其他关于新安装的 Visual Studio 的跨平台 Xamarin 应用程序

sql - 为所有表创建 Xamarin SQLite 数据库

c# - Instagram 到带有 RestSharp 的 TableView

ios - Xamarin 在 Storyboard 中实例化初始导航 Controller

android - 在 Xamarin 表单中拖放

javascript - 如何在外部浏览器中打开 anchor 标记链接,而不是在 xamarin.forms 中的同一 Web View 中打开

wpf - 在 VS2017 Xamarin 上拆分 'designer' 和 'source' 窗口?

c# - 使用 Xamarin.Auth 进行 OAuth2 身份验证 - 用户名和密码?

c# - SQLite Net PCL 慢 SELECT 查询

visual-studio - 我可以使用 Visual Studio 2017 Pro 安装 Xamarin Android 10.0 吗?