notificationManager get notification by Id
Asked Answered
E

3

13

Anyone know any way to get a notification by id? It's I want when get a new notification if it is still being shown in the status bar of Android want to get the information and add it to a new notification. Thank you.

Esotropia answered 23/5, 2014 at 13:58 Comment(1)
Please, accept the second answer.Communistic
R
17

NotificationManager doesn't give you a way to find existing notifications by ID. If you want to update a notification, post a new notification but use the same ID. It will either show it as new or update the existing notification with that ID.

Regent answered 23/5, 2014 at 14:34 Comment(4)
This will replace the old notification?Esotropia
Straight from the documentation: "If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information." developer.android.com/reference/android/app/…Regent
Thanks Karakuri, I solved my problem using sharedpreferences I store data in it and I use on update.Esotropia
As of Marshmallow (SDK 23) this answer is no longer correct. See @hakanbing's answer about getActiveNotifications().Playground
G
15

You can get active notification list from 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;
}
Granophyre answered 17/11, 2017 at 7:35 Comment(3)
requires API 23 and aboveFlimflam
Shows only visible notifications, which have been posted by OS.Here
@Anup but this returns only partial data like title and text and do not return full object of notificationCoccid
C
0

Thanks to @hakanbing the same in 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
}
Communistic answered 19/12, 2022 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.