【问题标题】:notificationManager get notification by IdnotificationManager 通过 Id 获取通知
【发布时间】:2014-05-23 13:58:48
【问题描述】:

有人知道通过 id 获取通知的方法吗?如果它仍然显示在Android的状态栏中,我希望在收到新通知时获取信息并将其添加到新通知中。谢谢。

【问题讨论】:

    标签: android notificationmanager


    【解决方案1】:

    NotificationManager 无法让您按 ID 查找现有通知。如果您想更新通知,请发布新通知但使用相同的 ID。它会将其显示为新通知或使用该 ID 更新现有通知。

    【讨论】:

    • 这将取代旧通知?
    • 直接来自文档:“如果您的应用程序已经发布了具有相同 id 的通知并且尚未取消,它将被更新的信息替换。” developer.android.com/reference/android/app/…
    • 感谢 Karakuri,我使用 sharedpreferences 解决了我的问题,我将数据存储在其中并在更新时使用。
    • 从 Marshmallow (SDK 23) 开始,这个答案不再正确。请参阅@hakanbing 关于 getActiveNotifications() 的回答。
    【解决方案2】:

    您可以从 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;
    }
    

    【讨论】:

    • 需要 API 23 及以上版本
    • 仅显示可见的通知,这些通知已由操作系统发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多