在我的应用中,我有一个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;
}
}
}
这里是结果:
已删除的通知:com.samepackage,1412915524994,-99,0
目标通知:com.samepackage,1412915524994,-99,0
false
==比较指向相同内存位置的objecs。(http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/)因此,与其比较对象,不如比较其id值。这可能可以解决您的问题。
if (notification.getId() == targetNotification.getId()) {
targetNotification = null;
}
摘自onNotificationRemoved (StatusBarNotification sbn)
的文档:
参数
sbn:至少封装原始数据的数据结构 用于发布广告的信息(标签和ID)和来源(程序包名称) 刚刚删除的通知。
所以我认为要比较两个通知,我们需要比较它们的标记,ID和程序包名称:
if (notification.getTag().equals(targetNotification.getTag()) &&
notification.getId() == targetNotification.getId() &&
notification.getPackageName().equals(targetNotification.getPackageName())) {
targetNotification = null;
}
编辑:注意,通知标签可以为空! (因此,上面的代码可能会抛出NPE)。确保对其进行控制。