Android NotificationListenerService onNotificationPosted fire twice

android, android-notification-bar, android-notifications

I listen for notifications like WhatsApp Messages.

But every time a notification comes in the NotificationListenerService fire twice.

Does anyone know this problem??

This is a snippet from the AndroidManifest.xml:

<service android:name=".NotifyService"            android:label="WhatsNotify"            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">    <intent-filter>                <action android:name="android.service.notification.NotificationListenerService"></action>    </intent-filter></service>

And inside the NotificationListenerService class:

public class NotifyService extends NotificationListenerService {    @Override    public void onNotificationPosted(StatusBarNotification sbn) {        Log.i("NotifyService", "got notification");    }}

Properties of both StatusBarNotifications:

First notification:

0|com.whatsapp|1|[email protected]|10073

Second notification:


Best Solution

I'm not sure why this happens. Maybe flags of notifications could be triggering it twice.

You can try to omit duplicate executing yourself:

public class NotifyService extends NotificationListenerService {    private String mPreviousNotificationKey;    @Override    public void onNotificationPosted(StatusBarNotification sbn) {        if(TextUtils.isEmpty(mPreviousNotification) || !TextUtils.isEmpty(mPreviousNotification) && !sbn.getKey().equals(mPreviousNotificationKey)){        Log.i("NotifyService", "got notification");    }}

Each StatusBarNotification has unique key which is generated:

private String key() {   return user.getIdentifier() + "|" + pkg + "|" + id + "|" + tag + "|" + uid;}

Holding each previous key can distinguish latter notification for given package.