【问题标题】:PendingIntent sticks around after notification is dismissed通知被驳回后,PendingIntent 仍然存在
【发布时间】:2017-08-15 00:27:11
【问题描述】:

我编写了以下方法来检查通知是否处于活动状态(在状态栏上可见):

public static boolean isNotificationActive(Context context, int id) {
  Intent intentPopup = new Intent(context, PopupActivity.class);
  PendingIntent test = PendingIntent.getActivity(context, id, intentPopup, PendingIntent.FLAG_NO_CREATE);
  return test != null;
}

我创建了一个与我想要检查的完全一样的 PendingIntent(相同的 'intentPopup' 和 'id' 被传递给这个 PendingIntent),并且由于 FLAG_NO_CREATE,如果它没有,我希望这个 PendingIntent 为空还存在。我在几年前发布的帖子中读到了这种方法。

如果尚未发出通知,则该方法返回预期值 (false)。当通知发出并在状态栏中时,该方法返回true。

但是,在我关闭通知后,该方法仍然返回 true,就好像 PendingIntent 仍然存在一样。

我在这里缺少什么? PendingIntent 仍然可用还是我误解了什么?

是否有更好的方法来检查特定通知是否处于活动状态(显示在状态栏中)?

编辑:这是创建通知的代码:

    Intent intentPopup = new Intent(context, PopupActivity.class);
            intentPopup.putExtra("id", id);
            intentPopup.putExtra("timeQ", timeQ);

    PendingIntent pendingIntentPopup = PendingIntent.getActivity(context, id, intentPopup, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                    .setContentIntent(pendingIntentPopup)
                    .setSmallIcon(R.drawable.q_notification_icon)
                    .setContent(contentView)
                    .setSound(Uri.parse("android.resource://" + context.getPackageName() + "/raw/notification_sound"))
                    .setVibrate(vibrate_pattern);

            Notification notification = mBuilder.build();
            notification.flags |= Notification.FLAG_NO_CLEAR;
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(id, notification);

【问题讨论】:

  • 发布你用来创建Notification的代码
  • @DavidWasser 已发布。

标签: android android-intent android-notifications android-pendingintent


【解决方案1】:

很遗憾,您嵌入在Notification 中的PendingIntents 不会在Notification 被关闭、查看或取消时自动消失。您不能使用 PendingIntent 的存在与否(像您所做的那样使用 PendingIntent.FLAG_NO_CREATE)来确定 Notification 是否处于活动状态。

要确定Notification 是否处于活动状态,您可以调用NotificationManager.getActiveNotifications()。这将返回您的应用发布的所有活动的Notifications。

【讨论】:

  • 我明白了。不幸的是,getActiveNotifications() 是在 API 23 中引入的,而我的应用程序的 minsdk 是 19 ......无论如何,谢谢@DavidWasser。我会继续寻找替代方案。
  • 另一种选择是使用NotificationListenerService。这是在 API 18 中引入的,因此您可以使用它。它有点复杂,但应该给你你想要的。有一个方法getActiveNotifications()。
猜你喜欢
  • 1970-01-01
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
  • 2017-03-28
  • 1970-01-01
相关资源
最近更新 更多