gra*_*att 6 android android-notifications android-notification-bar
我收听WhatsApp Messages等通知.
但每次通知都会在NotificationListenerService中触发两次.
有谁知道这个问题?
这是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>
Run Code Online (Sandbox Code Playgroud)
在NotificationListenerService类中:
public class NotifyService extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i("NotifyService", "got notification");
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:两者StatusBarNotification的属性:
第一次通知:
0|com.whatsapp|1|xxxxxxxxxx@s.whatsapp.net|10073
第二次通知:
0|com.whatsapp|1|null|10073
我不确定为什么会发生这种情况。也许通知标志可能会触发它两次。
您可以尝试自己省略重复执行:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
每个StatusBarNotification都有生成的唯一密钥:
private String key() {
return user.getIdentifier() + "|" + pkg + "|" + id + "|" + tag + "|" + uid;
}
Run Code Online (Sandbox Code Playgroud)
按住每个前一个键可以区分给定包的后一个通知。