Android NotificationListenerService onNotificationPosted fire twice

后端 未结 5 1017
情深已故
情深已故 2021-01-18 12:35

I listen for notifications like WhatsApp Messages.

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

Does anyone know this p

5条回答
  •  忘掉有多难
    2021-01-18 13:23

    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.

提交回复
热议问题