通知管理器通过ID获取通知。

13

有人知道如何通过id获取通知吗?我的意思是,当我收到新通知时,如果它仍在Android状态栏中显示,我想获取相关信息并将其添加到新的通知中。谢谢。


请接受第二个答案。 - CoolMind
3个回答

17

NotificationManager没有提供通过ID查找现有通知的方法。如果您想要更新通知,请发布一个新的通知,但使用相同的ID。它将显示为新的通知,或者更新具有该ID的现有通知。


这会替换旧的通知吗? - Gustavo Rozolin
1
直接从文档中摘录:“如果您的应用程序已经发布了具有相同ID的通知,并且尚未被取消,则它将被更新的信息替换。” https://developer.android.com/reference/android/app/NotificationManager.html#notify(int,%20android.app.Notification) - Karakuri
5
谢谢,我使用SharedPreferences解决了我的问题。我将数据存储在其中,并在更新时使用它。 - Gustavo Rozolin
1
从Marshmallow(SDK 23)开始,这个答案已经不正确了。请参考@hakanbing的getActiveNotifications()答案。 - Yojimbo

15

你可以从NotificationManager获取活动通知列表。

@RequiresApi(api = Build.VERSION_CODES.M)
public Notification getActiveNotification(int notificationId) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    StatusBarNotification[] barNotifications = notificationManager.getActiveNotifications();
    for(StatusBarNotification notification: barNotifications) {
        if (notification.getId() == notificationId) {
            return notification.getNotification();
        }
    }
    return null;
}

5
需要API 23及以上版本。 - Desolator
仅显示操作系统发布的可见通知。 - Michal Zhradnk Nono3551
@Anup 但是这只返回部分数据,比如标题和文本,并不返回完整的通知对象。 - Nitin

0
感谢 @hakanbing 提供的 Kotlin 版本。
fun getActiveNotification(context: Context, notificationId: Int): Notification? {
    val notificationManager =
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val barNotifications = notificationManager.activeNotifications
    return barNotifications.firstOrNull { it.id == notificationId }?.notification
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接