Java Code Examples for android.app.NotificationManager#getActiveNotifications()

The following examples show how to use android.app.NotificationManager#getActiveNotifications() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LaunchModeManager.java    From Phantom with Apache License 2.0 7 votes vote down vote up
/**
 * 如果应用启动的时候通知栏没有关于应用的通知,就删除为通知建立的占位Activity的固定映射关系.
 * 将占位activity空出来供其他activity使用
 * 但只有6.0及以上系统才有用。4.3到5.1系统需要特殊权限才能访问通知栏,这里不做兼容
 */
private void cleanCacheIfNeeded() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        try {
            // 1. 目前发现在OPPO R9S PLUST,OPPO R9SK,OPPO R9S,OPPO A57机器上 getActiveNotifications()
            //    可能抛出 NullPointerException 导致 Phantom 初始化失败(bugly显示程序都是在后台)
            // 2. 双开软件软件会导致 NotificationManager.getActiveNotifications 出现 SecurityException 。例如:
            //    https://bugly.qq.com/v2/crash-reporting/errors/900016079/201216/report?pid=1
            StatusBarNotification[] sbn = null == nm ? null : nm.getActiveNotifications();
            VLog.w("cleanCacheIfNeeded active notifications count is %d", null == sbn ? -1 : sbn.length);

            if (null != sbn && sbn.length == 0) {
                mCache.clean();
            }
        } catch (Exception e) {
            VLog.w(e, "NotificationManager.getActiveNotifications error!");
            LogReporter.reportException(e);
        }
    }
}
 
Example 2
Source File: DefaultMessageNotifier.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static boolean isDisplayingSummaryNotification(@NonNull Context context) {
  if (Build.VERSION.SDK_INT >= 23) {
    try {
      NotificationManager     notificationManager = ServiceUtil.getNotificationManager(context);
      StatusBarNotification[] activeNotifications = notificationManager.getActiveNotifications();

      for (StatusBarNotification activeNotification : activeNotifications) {
        if (activeNotification.getId() == NotificationIds.MESSAGE_SUMMARY) {
          return true;
        }
      }

      return false;

    } catch (Throwable e) {
      // XXX Android ROM Bug, see #6043
      Log.w(TAG, e);
      return false;
    }
  } else {
    return false;
  }
}
 
Example 3
Source File: DownloadNotificationService.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * @return The summary {@link StatusBarNotification} if one is showing.
 */
@TargetApi(Build.VERSION_CODES.M)
private static StatusBarNotification getSummaryNotification(NotificationManager manager) {
    if (!useForegroundService()) return null;

    StatusBarNotification[] notifications = manager.getActiveNotifications();
    for (StatusBarNotification notification : notifications) {
        boolean isDownloadsGroup = TextUtils.equals(notification.getNotification().getGroup(),
                NotificationConstants.GROUP_DOWNLOADS);
        boolean isSummaryNotification =
                notification.getId() == NotificationConstants.NOTIFICATION_ID_DOWNLOAD_SUMMARY;
        if (isDownloadsGroup && isSummaryNotification) return notification;
    }

    return null;
}
 
Example 4
Source File: DownloadNotificationService.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether or not there are any download notifications showing that aren't the summary
 * notification.
 * @param notificationIdToIgnore If not -1, the id of a notification to ignore and
 *                               assume is closing or about to be closed.
 * @return Whether or not there are valid download notifications currently visible.
 */
@TargetApi(Build.VERSION_CODES.M)
private static boolean hasDownloadNotifications(
        NotificationManager manager, int notificationIdToIgnore) {
    if (!useForegroundService()) return false;

    StatusBarNotification[] notifications = manager.getActiveNotifications();
    for (StatusBarNotification notification : notifications) {
        boolean isDownloadsGroup = TextUtils.equals(notification.getNotification().getGroup(),
                NotificationConstants.GROUP_DOWNLOADS);
        boolean isSummaryNotification =
                notification.getId() == NotificationConstants.NOTIFICATION_ID_DOWNLOAD_SUMMARY;
        boolean isIgnoredNotification =
                notificationIdToIgnore != -1 && notificationIdToIgnore == notification.getId();
        if (isDownloadsGroup && !isSummaryNotification && !isIgnoredNotification) return true;
    }

    return false;
}
 
Example 5
Source File: MessageNotifier.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
private static void cancelActiveNotifications(@NonNull Context context) {
  NotificationManager notifications = ServiceUtil.getNotificationManager(context);
  notifications.cancel(SUMMARY_NOTIFICATION_ID);

  if (Build.VERSION.SDK_INT >= 23) {
    try {
      StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();

      for (StatusBarNotification activeNotification : activeNotifications) {
        notifications.cancel(activeNotification.getId());
      }
    } catch (Throwable e) {
      // XXX Appears to be a ROM bug, see https://github.com/WhisperSystems/Signal-Android/issues/6043
      Log.w(TAG, e);
      notifications.cancelAll();
    }
  }
}
 
Example 6
Source File: RNPushNotificationHelper.java    From react-native-push-notification with MIT License 6 votes vote down vote up
public WritableArray getDeliveredNotifications() {
  NotificationManager notificationManager = notificationManager();
  StatusBarNotification delivered[] = notificationManager.getActiveNotifications();
  Log.i(LOG_TAG, "Found " + delivered.length + " delivered notifications");
  WritableArray result = Arguments.createArray();
  /*
    * stay consistent to the return structure in
    * https://facebook.github.io/react-native/docs/pushnotificationios.html#getdeliverednotifications
    * but there is no such thing as a 'userInfo'
    */
  for (StatusBarNotification notification : delivered) {
    Notification original = notification.getNotification();
    Bundle extras = original.extras;
    WritableMap notif = Arguments.createMap();
    notif.putString("identifier", "" + notification.getId());
    notif.putString("title", extras.getString(Notification.EXTRA_TITLE));
    notif.putString("body", extras.getString(Notification.EXTRA_TEXT));
    notif.putString("tag", notification.getTag());
    notif.putString("group", original.getGroup());
    result.pushMap(notif);
  }

  return result;

}
 
Example 7
Source File: MapUnzip.java    From PocketMaps with MIT License 6 votes vote down vote up
@TargetApi(ANDROID_API_MARSHMALLOW)
private static boolean checkUnzipAliveInternal(Context c, MyMap myMap)
{
  String unzipKeyId = myMap.getMapName() + "-unzip";
  NotificationManager notificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
  
  for (StatusBarNotification n : notificationManager.getActiveNotifications())
  {
    if (n.getId() == unzipKeyId.hashCode())
    {
      long postTime = n.getPostTime();
      return timeCheck(postTime);
    }
  }
  return false;
}
 
Example 8
Source File: ProgressPublisher.java    From PocketMaps with MIT License 6 votes vote down vote up
@TargetApi(26) //OREO
private void updateTextFinalOrio(String txt)
{ // Crazy: Android is blocking when too much notification updates, so final message does not receive. Try later :(
  int sleepTime = 300;
  for (int i=0; i<10; i++)
  {
    updateTextFinalInternal(txt);
    NotificationManager nMgr = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
    boolean found = false;
    for (StatusBarNotification n : nMgr.getActiveNotifications())
    {
      if (n.getId() != id) { continue; }
      found = true;
      if (!n.isOngoing()) { return; }
    }
    if (!found) { return; }
    try { Thread.sleep(sleepTime); } catch (Exception e) {}
    sleepTime = (sleepTime/2) * 3;
  }
}
 
Example 9
Source File: NotificationController.java    From MiPushFramework with GNU General Public License v3.0 6 votes vote down vote up
public static void cancel(Context context, int id) {
    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    String groupId = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        StatusBarNotification[] activeNotifications = manager.getActiveNotifications();
        for (StatusBarNotification activeNotification : activeNotifications) {
            if (activeNotification.getId() == id) {
                groupId = activeNotification.getNotification().getGroup();
                break;
            }

        }
    }

    manager.cancel(id);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        if (groupId != null) {
            updateSummaryNotification(context, NotificationUtils.getPackageName(groupId), groupId);
        }
    }
}
 
Example 10
Source File: DefaultMessageNotifier.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static void cancelActiveNotifications(@NonNull Context context) {
  NotificationManager notifications = ServiceUtil.getNotificationManager(context);
  notifications.cancel(NotificationIds.MESSAGE_SUMMARY);

  if (Build.VERSION.SDK_INT >= 23) {
    try {
      StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();

      for (StatusBarNotification activeNotification : activeNotifications) {
        if (!CallNotificationBuilder.isWebRtcNotification(activeNotification.getId())) {
          notifications.cancel(activeNotification.getId());
        }
      }
    } catch (Throwable e) {
      // XXX Appears to be a ROM bug, see #6043
      Log.w(TAG, e);
      notifications.cancelAll();
    }
  }
}
 
Example 11
Source File: CallNotificationManager.java    From react-native-twilio-programmable-voice with MIT License 5 votes vote down vote up
public void removeIncomingCallNotification(ReactApplicationContext context,
                                           CallInvite callInvite,
                                           int notificationId) {
    Log.d(TAG, "removeIncomingCallNotification");
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        if (callInvite != null && callInvite.getState() == CallInvite.State.PENDING) {
            /*
             * If the incoming call message was cancelled then remove the notification by matching
             * it with the call sid from the list of notifications in the notification drawer.
             */
            StatusBarNotification[] activeNotifications = notificationManager.getActiveNotifications();
            for (StatusBarNotification statusBarNotification : activeNotifications) {
                Notification notification = statusBarNotification.getNotification();
                String notificationType = notification.extras.getString(NOTIFICATION_TYPE);
                if (callInvite.getCallSid().equals(notification.extras.getString(CALL_SID_KEY)) &&
                        notificationType != null && notificationType.equals(ACTION_INCOMING_CALL)) {
                    notificationManager.cancel(notification.extras.getInt(INCOMING_CALL_NOTIFICATION_ID));
                }
            }
        } else if (notificationId != 0) {
            notificationManager.cancel(notificationId);
        }
    } else {
        if (notificationId != 0) {
            notificationManager.cancel(notificationId);
        } else if (callInvite != null) {
            String notificationKey = INCOMING_NOTIFICATION_PREFIX+callInvite.getCallSid();
            if (TwilioVoiceModule.callNotificationMap.containsKey(notificationKey)) {
                notificationId = TwilioVoiceModule.callNotificationMap.get(notificationKey);
                notificationManager.cancel(notificationId);
                TwilioVoiceModule.callNotificationMap.remove(notificationKey);
            }
        }
    }
}
 
Example 12
Source File: Manager.java    From cordova-plugin-firebase-extended-notification with MIT License 5 votes vote down vote up
public boolean notificationExists(int notificationId) {
    NotificationManager notificationManager = (NotificationManager)
        this.context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= 23) {
        StatusBarNotification[] notifications = notificationManager
            .getActiveNotifications();
        for (StatusBarNotification notification : notifications)
            if (notification.getId() == notificationId)
                return true;
        return false;
    }
    //If lacks support
    return true;
}
 
Example 13
Source File: NotificationReceiver.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 5 votes vote down vote up
private void updateCurrentNotifications(NotificationFetchData notificationFetchData, NotificationManager notificationManager, Context context) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return;
    }

    // This try-catch is needed because of an Android 6.0 issue where calling getActiveNotifications may throw a nullpointerexception
    // https://github.com/googlesamples/android-ActiveNotifications/issues/1
    try {
        if (notificationManager == null || notificationManager.getActiveNotifications() == null) {
            return;
        }
    } catch (NullPointerException e) {
        return;
    }


    // Nested for loops :/
    for (StatusBarNotification statusBarNotification : notificationManager.getActiveNotifications()) {
        for (StreamInfo stream : notificationFetchData.getCurrentlyOnlineStreams()) {
            if (stream.getChannelInfo().getNotificationTag().equals(statusBarNotification.getTag())) {
                Notification notification = createStreamNotification(
                        stream,
                        getLargeIconFromNotification(statusBarNotification.getNotification(), context),
                        true,
                        context
                );

                notificationManager.notify(
                        stream.getChannelInfo().getNotificationTag(),
                        NOTIFICATION_ID,
                        notification
                );
            }
        }
    }
}
 
Example 14
Source File: MessageNotifier.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private static void cancelOrphanedNotifications(@NonNull Context context, NotificationState notificationState) {
  if (Build.VERSION.SDK_INT >= 23) {
    try {
      NotificationManager     notifications       = ServiceUtil.getNotificationManager(context);
      StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();

      for (StatusBarNotification notification : activeNotifications) {
        boolean validNotification = false;

        if (notification.getId() != SUMMARY_NOTIFICATION_ID) {
          for (NotificationItem item : notificationState.getNotifications()) {
            if (notification.getId() == (SUMMARY_NOTIFICATION_ID + item.getThreadId())) {
              validNotification = true;
              break;
            }
          }

          if (!validNotification) {
            notifications.cancel(notification.getId());
          }
        }
      }
    } catch (Throwable e) {
      // XXX Android ROM Bug, see https://github.com/WhisperSystems/Signal-Android/issues/6043
      Log.w(TAG, e);
    }
  }
}
 
Example 15
Source File: DefaultMessageNotifier.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private static void cancelOrphanedNotifications(@NonNull Context context, NotificationState notificationState) {
  if (Build.VERSION.SDK_INT >= 23) {
    try {
      NotificationManager     notifications       = ServiceUtil.getNotificationManager(context);
      StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();

      for (StatusBarNotification notification : activeNotifications) {
        boolean validNotification = false;

        if (notification.getId() != NotificationIds.MESSAGE_SUMMARY       &&
            notification.getId() != KeyCachingService.SERVICE_RUNNING_ID  &&
            notification.getId() != IncomingMessageObserver.FOREGROUND_ID &&
            notification.getId() != NotificationIds.PENDING_MESSAGES      &&
            !CallNotificationBuilder.isWebRtcNotification(notification.getId()))
        {
          for (NotificationItem item : notificationState.getNotifications()) {
            if (notification.getId() == NotificationIds.getNotificationIdForThread(item.getThreadId())) {
              validNotification = true;
              break;
            }
          }

          if (!validNotification) {
            notifications.cancel(notification.getId());
          }
        }
      }
    } catch (Throwable e) {
      // XXX Android ROM Bug, see #6043
      Log.w(TAG, e);
    }
  }
}
 
Example 16
Source File: NotUsedMobileCellsNotificationDisableReceiver.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    //PPApplication.logE("##### NotUsedMobileCellsNotificationDisableReceiver.onReceive", "xxx");

    //CallsCounter.logCounter(context, "NotUsedMobileCellsNotificationDisableReceiver.onReceive", "NotUsedMobileCellsNotificationDisableReceiver_onReceive");

    SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context.getApplicationContext());
    editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_MOBILE_CELL_NOT_USED_CELLS_DETECTION_NOTIFICATION_ENABLED, false);
    editor.apply();
    ApplicationPreferences.applicationEventMobileCellNotUsedCellsDetectionNotificationEnabled(context.getApplicationContext());

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (manager != null) {
        //if (Build.VERSION.SDK_INT >= 23) {
            StatusBarNotification[] notifications = manager.getActiveNotifications();
            for (StatusBarNotification notification : notifications) {
                String tag = notification.getTag();
                if ((tag != null) && tag.contains(PPApplication.NEW_MOBILE_CELLS_NOTIFICATION_TAG+"_")) {
                    if (notification.getId() >= PPApplication.NEW_MOBILE_CELLS_NOTIFICATION_ID) {
                        manager.cancel(notification.getTag(), notification.getId());
                    }
                }
            }
        /*} else {
            int notificationId = intent.getIntExtra("notificationId", 0);
            manager.cancel(notificationId);
        }*/
    }
}
 
Example 17
Source File: Permissions.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
static void removeProfileNotification(Context context)
{
    try {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.cancel(
                    PPApplication.GRANT_PROFILE_PERMISSIONS_NOTIFICATION_TAG,
                    PPApplication.GRANT_PROFILE_PERMISSIONS_NOTIFICATION_ID);
            //if (Build.VERSION.SDK_INT >= 23) {
            StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
            for (StatusBarNotification notification : notifications) {
                String tag = notification.getTag();
                if ((tag != null) && tag.contains(PPApplication.GRANT_PROFILE_PERMISSIONS_NOTIFICATION_TAG+"_")) {
                    if (notification.getId() >= PPApplication.PROFILE_ID_NOTIFICATION_ID) {
                        notificationManager.cancel(notification.getTag(), notification.getId());
                    }
                }
            }
        /*} else {
            int notificationId = intent.getIntExtra("notificationId", 0);
            manager.cancel(notificationId);
        }*/
        }
    } catch (Exception e) {
        PPApplication.recordException(e);
    }
}
 
Example 18
Source File: Permissions.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
static void removeEventNotification(Context context)
{
    try {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.cancel(
                    PPApplication.GRANT_EVENT_PERMISSIONS_NOTIFICATION_TAG,
                    PPApplication.GRANT_EVENT_PERMISSIONS_NOTIFICATION_ID);
            //if (Build.VERSION.SDK_INT >= 23) {
            StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
            for (StatusBarNotification notification : notifications) {
                String tag = notification.getTag();
                if ((tag != null) && tag.contains(PPApplication.GRANT_EVENT_PERMISSIONS_NOTIFICATION_TAG+"_")) {
                    if (notification.getId() >= PPApplication.EVENT_ID_NOTIFICATION_ID) {
                        notificationManager.cancel(notification.getTag(), notification.getId());
                    }
                }
            }
        /*} else {
            int notificationId = intent.getIntExtra("notificationId", 0);
            manager.cancel(notificationId);
        }*/
        }
    } catch (Exception e) {
        PPApplication.recordException(e);
    }
}
 
Example 19
Source File: AlarmHandler.java    From openScale with GNU General Public License v3.0 5 votes vote down vote up
private void cancelAlarmNotification(Context context)
{
    NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    {
        StatusBarNotification[] activeNotifications = mNotifyMgr.getActiveNotifications();
        for (StatusBarNotification notification : activeNotifications)
        {
            if (notification.getId() == ALARM_NOTIFICATION_ID) mNotifyMgr.cancel(ALARM_NOTIFICATION_ID);
        }
    }
    else mNotifyMgr.cancel(ALARM_NOTIFICATION_ID);
}
 
Example 20
Source File: NotificationController.java    From MiPushFramework with GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.N)
private static void updateSummaryNotification(Context context, String packageName, String groupId) {
    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    StatusBarNotification[] activeNotifications = manager.getActiveNotifications();

    
    int notificationCntInGroup = 0;
    for (StatusBarNotification statusBarNotification : activeNotifications) {
        if (groupId.equals(statusBarNotification.getNotification().getGroup())) {
            notificationCntInGroup++;
        }
    }

    if (notificationCntInGroup > 1) {

        CharSequence appName = ApplicationNameCache.getInstance().getAppName(context, packageName);

        Bundle extras = new Bundle();
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new Notification.Builder(context, getChannelIdByPkg(packageName));
            builder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN);
        } else {
            builder = new Notification.Builder(context);
        }

        int color = getIconColor(context, packageName);
        if (color != Notification.COLOR_DEFAULT) {
            CharSequence subText = ColorUtil.createColorSubtext(appName, color);
            if (subText != null) {
                extras.putCharSequence(NotificationCompat.EXTRA_SUB_TEXT, subText);
            }
            builder.setColor(color);
        } else {
            extras.putCharSequence(NotificationCompat.EXTRA_SUB_TEXT, appName);
        }

        builder.setExtras(extras);

        // Set small icon
        NotificationController.processSmallIcon(context, packageName, builder);

        builder.setCategory(Notification.CATEGORY_EVENT)
                .setGroupSummary(true)
                .setGroup(groupId);
        Notification notification = builder.build();
        manager.notify(packageName.hashCode(), notification);
    } else {
        manager.cancel(packageName.hashCode());
    }
}