Android NotificationListenerService onNotificationPost触发两次 [英] Android NotificationListenerService onNotificationPosted fire twice

查看:326
本文介绍了Android NotificationListenerService onNotificationPost触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收听诸如WhatsApp消息之类的通知.

I listen for notifications like WhatsApp Messages.

但是,每次NotificationListenerService中有一条通知时,都会触发两次.

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

有人知道这个问题吗?

这是AndroidManifest.xml的摘录:

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>

在NotificationListenerService类中:

And inside the NotificationListenerService class:

public class NotifyService extends NotificationListenerService {

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

修改: 这两个StatusBarNotification的属性:

第一个通知:

0|com.whatsapp|1|xxxxxxxxxx@s.whatsapp.net|10073

第二通知:

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");
    }
}

每个StatusBarNotification具有生成的唯一密钥:

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.

这篇关于Android NotificationListenerService onNotificationPost触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆