【问题标题】:Setting and canceling alarms with AlarmManager (Android)使用 AlarmManager (Android) 设置和取消闹钟
【发布时间】:2012-09-25 13:07:03
【问题描述】:

这是一篇请求确认(或反驳)我认为 Android 中的警报会发生什么的帖子。这个主题在博客和 StackOverflow 帖子中经常出现,但我还没有找到对这两点的明确解释(如下)。

下面的代码用于设置和报警,然后取消设置。它不起作用。

    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.setAction(AlarmReceiver.ALERT_GUARD_CHECKIN);
    PendingIntent sender = PendingIntent.getBroadcast(context, _id, intent,
            PendingIntent.FLAG_ONE_SHOT);

    AlarmManager am = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, now.getTime().getTime(), sender);

    Intent toCancel = new Intent(context, AlarmReceiver.class);
    toCancel.setAction(AlarmReceiver.ALERT_GUARD_CHECKIN);
    PendingIntent pendingToCancel = PendingIntent.getBroadcast(context,
            _id, toCancel, PendingIntent.FLAG_CANCEL_CURRENT);
    am.cancel(pendingToCancel);

如果不是将 PendingIntent.FLAG_ONE_SHOT 传递给 PendingIntent.getBroadast() 的第一次调用,而是传递零,它确实有效。我不相信这种行为被记录在案。

如果 PendingIntent.getBroadast() 的第二个参数(上图,_id)不相同,该代码也不起作用。我不相信这是记录在案的。在 Android 文档中,第二个参数记录为“发件人的私人请求代码(当前未使用)。”

问题是我是否正确地描述了这种行为,或者这些概括是否是表象。

【问题讨论】:

    标签: android alarmmanager


    【解决方案1】:

    您必须将PendingIntent 传递给cancel(),这与您用来注册警报的那个相同。这意味着使用相同的意图、标志和请求代码。与文档可能让您相信的相反,它实际上也检查了请求代码值。

    【讨论】:

    • 好的,感谢您的确认。这是包含在文档中的重要内容!
    【解决方案2】:

    您的 Android 清单中定义的警报是否有接收器?

    【讨论】:

    • 是的,我收到警报很好(或者没有,如果我按照上面的描述删除它)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多