如何检测它是否与StatusBarNotification相同

时间:2014-10-10 04:31:12

标签: android android-notifications

在我的应用中,我有一个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

     

目标noti:com.samepackage,1412915524994,-99,0

     

2 个答案:

答案 0 :(得分:0)

==比较指向相同内存位置的对象。( http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/) 所以不要比较对象,请比较它的id值。这可能会解决你的问题。

 if (notification.getId() == targetNotification.getId()) {
             targetNotification = null;
     }

答案 1 :(得分:0)

来自onNotificationRemoved (StatusBarNotification sbn)的文档:

  

参数

     

sbn:至少封装原始数据的数据结构   用于发布的信息(标签和标识)和来源(包名)   刚刚删除的通知。

所以我想比较两个通知,我们需要比较它们的标签,ID和包名称:

    if (notification.getTag().equals(targetNotification.getTag()) && 
        notification.getId() == targetNotification.getId() && 
        notification.getPackageName().equals(targetNotification.getPackageName())) {
                targetNotification = null;
    }