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");
}
}
Edit:
Properties of both StatusBarNotification
s:
First notification:
0|com.whatsapp|1|xxxxxxxxxx@s.whatsapp.net|10073
Second notification:
0|com.whatsapp|1|null|10073
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.