Marcus
Marcus

Reputation: 627

How to detect whether notification id exists or not?

Is it possible to detect if a notification attached with a unique id exists in the notifications bar?

mNotificationManager.notify(100, mBuilder.build());

For example, I created the notification with id 100. Next time when I create a notification with that id again, I don't want it updated. I used setOnlyAlertOnce(true), the sound is gone but it still updates that notification and moves it to the top.

Upvotes: 6

Views: 4987

Answers (2)

Paijo Anita Sari
Paijo Anita Sari

Reputation: 1

private lateinit var manager2: NotificationManager
manager2 = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

val notificationDownload: Array<StatusBarNotification> = manager2.activeNotifications
if (notificationDownload.isNotEmpty()) {
    for (notification in notificationDownload) {
     if (notification.id == 11223344) { // id notif on showing
       // Write your condition if id is equal same as notification id on show status bar
     } else {
       // Write your condition if id not equal as notif status bar.
     }
   }
} else { // Your condition if empty notif in status bar }

Upvotes: 0

Michael
Michael

Reputation: 54705

Starting from API Level 23 (Android M) you can get a list of active notifications and find a notification with a given id.

StatusBarNotification[] notifications = 
    mNotificationManager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
  if (notification.getId() == 100) {
    // Do something.
  }
}

On earlier versions you need to persist information about notifications you created and handle notification deletion by setting deleteIntent when creating a notification.

Upvotes: 10

Related Questions