【问题标题】:Cancel and Re-create new PendingIntent取消并重新创建新的 PendingIntent
【发布时间】:2015-05-04 06:09:56
【问题描述】:

我正在我的游戏中创建通知。如果玩家有一段时间没有玩游戏,我想显示通知。我正在使用下面的带有警报设置的 PendingIntent 来创建通知。有了这个我可以创建通知。

问题:如果玩家玩游戏,我需要取消现有的待处理 Intent 并创建一个新的待处理 Intent。我希望 Pending Intent 标志将用于实现?请指教。如果您能对可用的标志有所了解,那将是一个很大的帮助。

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

【问题讨论】:

  • 为什么要取消PendingIntent并创建一个新的?请提供更多数据,以便我正确回答您的问题。
  • 基本上我会在用户离开游戏时设置pending intent。这将在 5 天后触发通知。如果用户在 5 天内玩游戏,我应该取消计划在 5 天后触发的 pendingIntent。在此之后,当玩家退出游戏时,我将再次设置待定意图,该意图将在 5 天后触发。
  • 所以您没有使用PendingIntent 创建Notification。您将PendingIntent 发送到AlarmManager 以设置警报。对吗?

标签: android android-intent android-pendingintent


【解决方案1】:

取消使用FLAG_ONE_SHOT 创建的PendingIntent 的唯一方法是保留对该PendingIntent 的引用,然后在该引用上调用cancel()

如果您不再有参考,则无法取消此PendingIntent

你不需要使用FLAG_ONE_SHOT,所以我不会那样做。它带来的问题多于解决的问题。

根据您在 cmets 中对我的问题的回答,您要做的是取消警报。您无需取消PendingIntent。要取消闹钟,只需执行以下操作:

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);

如果您在PendingIntent 中没有任何“附加”,那么您可以像这样创建您的PendingIntent

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

如果您在重置警报时需要替换PendingIntent 中的“额外”,您可以像这样创建PendingIntent

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
                          PendingIntent.FLAG_UPDATE_CURRENT);

【讨论】:

  • 感谢您理解我的问题和明确的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
相关资源
最近更新 更多