Android 如何检测它是否';这是相同的状态通知
在我的应用程序中,我有一个监听所有通知的Android 如何检测它是否';这是相同的状态通知,android,android-notifications,Android,Android Notifications,在我的应用程序中,我有一个监听所有通知的NotificationListenerService。我有一个StatusBarNotification字段,在发布某个通知时分配该字段,在删除通知时将其取消。在取消之前,我必须检查它是否与我之前分配的StatusBarNotification相同。但是,使用==操作符进行检查时,即使它是完全相同的通知,也不能按预期工作。那么我如何比较它们呢 public class NotificationListener extends NotificationLi
NotificationListenerService
。我有一个StatusBarNotification
字段,在发布某个通知时分配该字段,在删除通知时将其取消。在取消之前,我必须检查它是否与我之前分配的StatusBarNotification
相同。但是,使用==
操作符进行检查时,即使它是完全相同的通知,也不能按预期工作。那么我如何比较它们呢
public class NotificationListener extends NotificationListenerService {
private StatusBarNotification targetNotification;
@Override
public void onNotificationPosted(StatusBarNotification notification) {
if (targetNotification == null && notification.isClearable()) {
targetNotification = notification;
}
}
@Override
public void onNotificationRemoved(StatusBarNotification notification) {
System.out.println("removed noti: " + notification.getPackageName() + ", " + notification.getPostTime()+", "+notification.getId()+", "+notification.getUserId());
System.out.println("target noti: " + targetNotification.getPackageName() + ", " + targetNotification.getPostTime()+", "+targetNotification.getId()+", "+targetNotification.getUserId());
System.out.println(notification == targetNotification);
if (notification == targetNotification) {
targetNotification = null;
}
}
}
结果如下:
删除noti:com.samepackage,1412915524994,-99,0
target noti:com.samepackage,1412915524994,-99,0
假的
==比较指向相同内存位置的对象。() ) 因此,请比较它的id值,而不是与对象进行比较。这也许能解决你的问题
if (notification.getId() == targetNotification.getId()) {
targetNotification = null;
}
从
onNotificationRemoved(statusbarnotificationsbn)
的文档中:
参数
sbn:至少封装原始数据的数据结构
用于发布的信息(标签和id)和源(包名称)
刚刚删除的通知
因此,我认为要比较两个通知,我们需要比较它们的标记、id和包名:
if (notification.getTag().equals(targetNotification.getTag()) &&
notification.getId() == targetNotification.getId() &&
notification.getPackageName().equals(targetNotification.getPackageName())) {
targetNotification = null;
}
编辑:小心,通知标签可以为空!(因此,上面的代码可能会抛出NPE)。确保对其进行控制。但是您确定
getId()
为不同的通知返回唯一的值吗?我在notify method parameter id中找不到任何关于此的文档。此通知的标识符在您的应用程序中是唯一的。在您的应用程序中是唯一的
,但我认为对几个应用程序来说不是唯一的?这意味着来自Facebook的通知和来自社交网站的通知可能具有相同的id值,对吗?我明白你的问题。是的,可能是