java - Android onNotificationPosted 被 gmail 和 whatsApp 调用两次

标签 java android notifications notification-listener

我知道这看起来像是 Android NotificationListenerService onNotificationPosted fire twice 的副本和 NotificationListenerService onNotificationPosted() called multiple times for single Notification when it is part of grouped notification ,但我已经尝试了他们的解决方案,但它们似乎不起作用。

我想要做的就是拥有一个后台服务,计算一个人在电话中收到的通知数量,然后将其写入文本文件。

它适用于 SMS 和 Hangout 通知(即每个通知只触发一次)但是当我使用 WhatsApp 和 Gmail 测试它时,它会被触发两次,因此,对于每个 Gmail 通知,我的列表中有两行文本文件。

这是我的代码。任何帮助将不胜感激。

public class NotifCounterService extends NotificationListenerService {

   public static String TAG = NotifCounterService.class.getSimpleName();

   Date dateStart;

   private Logger logger;

   private Context mContext;

   @Override
   public void onCreate() {
      Log.d(TAG, "Created");

      logger = new Logger(TAG);
      mContext = getApplicationContext();
   }

   @Override
   public IBinder onBind(Intent intent) {
      return super.onBind(intent);
   }

   @Override
   public void onNotificationPosted(StatusBarNotification sbn) {

      Log.d(TAG, "Notification has arrived");

      Log.d(TAG, "ID: " + sbn.getId() + " Posted by: " + sbn.getPackageName() + " at: " + sbn.getPostTime() + " ");

      logger.i(sbn.getId() + "," + sbn.getPackageName() + "," + sbn.getPostTime(), mContext);
      logger.close();

      /*
       * Log.i(TAG, "ID:" + sbn.getId()); Log.i(TAG, "Posted by:" +
       * sbn.getPackageName()); Log.i(TAG, "tickerText:" +
       * sbn.getNotification().tickerText);
       */

      /*
       * for (String key : sbn.getNotification().extras.keySet()) { Log.i(TAG, key +
       * "=" + sbn.getNotification().extras.get(key).toString()); }
       */

   }
}

最佳答案

发生这种情况是因为 WhatsApp 和 Gmail 会在发送其他通知的同时发送群组摘要通知。

相关标志记录在此处:https://developer.android.com/reference/android/app/Notification.html#FLAG_GROUP_SUMMARY

您可以像这样使用此标志忽略通知:

   @Override
   public void onNotificationPosted(StatusBarNotification sbn) {
          if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
                  //Ignore the notification
                  return;
          }

          //...
   }

关于java - Android onNotificationPosted 被 gmail 和 whatsApp 调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45890487/

相关文章:

java - 运行Applet后没有任何显示

java - 嵌套异常是 org.springframework.beans.factory.BeanCreationException : Could not autowire field in restful web services

android - Android可以被外围设备从 sleep 状态唤醒吗?

node.js - 使用 Node.js 通过自定义 API 向设备(ios 或 android)发送通知

java - 组合组件放在哪里?(JSF 2.0)

java - sun.security.ssl.allowUnsafeRenegotiation

java - Android中如何重用onClickListener

java - 出于想法,MySQLNonTransientConnectionException : Could not create connection to database server

java - 在自定义内容通知中使用后更新 RemoteView

ios - 使用通知执行 segue 后 ViewController deinit