Example usage for android.app NotificationManager getActiveNotifications

List of usage examples for android.app NotificationManager getActiveNotifications

Introduction

In this page you can find the example usage for android.app NotificationManager getActiveNotifications.

Prototype

public StatusBarNotification[] getActiveNotifications() 

Source Link

Document

Recover a list of active notifications: ones that have been posted by the calling app that have not yet been dismissed by the user or #cancel(String,int) ed by the app.

Usage

From source file:com.actinarium.nagbox.service.NotificationHelper.java

/**
 * Cancel the notification by provided ID. On Android N will also cancel the summary notification if it's the last
 * child being removed.//from   w w w . j  a  v a 2  s  . c o m
 *
 * @param context        context
 * @param notificationId ID of the notification to cancel
 */
public static void cancelNotification(Context context, int notificationId) {
    final NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
    managerCompat.cancel(notificationId);

    // Apparently N doesn't cancel summary notification when all individual ones are cancelled
    // So we have to do it ourselves
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        NotificationManager manager = context.getSystemService(NotificationManager.class);
        final StatusBarNotification[] notifs = manager.getActiveNotifications();
        if (notifs.length == 1 && notifs[0].getId() == NAG_NOTIFICATION_ID && notifs[0].isGroup()) {
            // This must be the remaining summary. Clear it away
            managerCompat.cancel(NAG_NOTIFICATION_ID);
        }
    }
}

From source file:com.google.android.apps.muzei.datalayer.ActivateMuzeiIntentService.java

public static void maybeShowActivateMuzeiNotification(Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    if (preferences.getBoolean(ACTIVATE_MUZEI_NOTIF_SHOWN_PREF_KEY, false)) {
        return;//from   w  w  w .  j av a 2s.c o  m
    }
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(NOTIFICATION_SERVICE);
    StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
    boolean hasInstallNotification = false;
    boolean hasActivateNotification = false;
    for (StatusBarNotification notification : notifications) {
        if (notification.getId() == INSTALL_NOTIFICATION_ID) {
            hasInstallNotification = true;
        } else if (notification.getId() == ACTIVATE_NOTIFICATION_ID) {
            hasActivateNotification = true;
        }
    }
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.ic_stat_muzei)
            .setColor(ContextCompat.getColor(context, R.color.notification))
            .setPriority(NotificationCompat.PRIORITY_MAX).setDefaults(NotificationCompat.DEFAULT_VIBRATE)
            .setAutoCancel(true).setContentTitle(context.getString(R.string.activate_title));
    Intent deleteIntent = new Intent(context, ActivateMuzeiIntentService.class);
    deleteIntent.setAction(ACTION_MARK_NOTIFICATION_READ);
    builder.setDeleteIntent(PendingIntent.getService(context, 0, deleteIntent, 0));
    // Check if the Muzei main app is installed
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context).addApi(Wearable.API).build();
    ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
    Set<Node> nodes = new TreeSet<>();
    if (connectionResult.isSuccess()) {
        nodes = Wearable.CapabilityApi
                .getCapability(googleApiClient, "activate_muzei", CapabilityApi.FILTER_ALL).await()
                .getCapability().getNodes();
        googleApiClient.disconnect();
    }
    if (nodes.isEmpty()) {
        if (hasInstallNotification) {
            // No need to repost the notification
            return;
        }
        // Send an install Muzei notification
        if (PlayStoreAvailability.getPlayStoreAvailabilityOnPhone(
                context) != PlayStoreAvailability.PLAY_STORE_ON_PHONE_AVAILABLE) {
            builder.setContentText(context.getString(R.string.activate_no_play_store));
            FirebaseAnalytics.getInstance(context).logEvent("activate_notif_no_play_store", null);
        } else {
            builder.setContentText(context.getString(R.string.activate_install_muzei));
            Intent installMuzeiIntent = new Intent(context, ActivateMuzeiIntentService.class);
            installMuzeiIntent.setAction(ACTION_REMOTE_INSTALL_MUZEI);
            PendingIntent pendingIntent = PendingIntent.getService(context, 0, installMuzeiIntent, 0);
            builder.addAction(new NotificationCompat.Action.Builder(R.drawable.open_on_phone,
                    context.getString(R.string.activate_install_action), pendingIntent)
                            .extend(new NotificationCompat.Action.WearableExtender()
                                    .setHintDisplayActionInline(true).setAvailableOffline(false))
                            .build());
            builder.extend(new NotificationCompat.WearableExtender().setContentAction(0));
            FirebaseAnalytics.getInstance(context).logEvent("activate_notif_play_store", null);
        }
        notificationManager.notify(INSTALL_NOTIFICATION_ID, builder.build());
        return;
    }
    // else, Muzei is installed on the phone/tablet, but not activated
    if (hasInstallNotification) {
        // Clear any install Muzei notification
        notificationManager.cancel(INSTALL_NOTIFICATION_ID);
    }
    if (hasActivateNotification) {
        // No need to repost the notification
        return;
    }
    String nodeName = nodes.iterator().next().getDisplayName();
    builder.setContentText(context.getString(R.string.activate_enable_muzei, nodeName));
    Intent launchMuzeiIntent = new Intent(context, ActivateMuzeiIntentService.class);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, launchMuzeiIntent, 0);
    builder.addAction(new NotificationCompat.Action.Builder(R.drawable.open_on_phone,
            context.getString(R.string.activate_action, nodeName), pendingIntent)
                    .extend(new NotificationCompat.Action.WearableExtender().setHintDisplayActionInline(true)
                            .setAvailableOffline(false))
                    .build());
    Bitmap background = null;
    try {
        background = BitmapFactory.decodeStream(context.getAssets().open("starrynight.jpg"));
    } catch (IOException e) {
        Log.e(TAG, "Error reading default background asset", e);
    }
    builder.extend(new NotificationCompat.WearableExtender().setContentAction(0).setBackground(background));
    FirebaseAnalytics.getInstance(context).logEvent("activate_notif_installed", null);
    notificationManager.notify(ACTIVATE_NOTIFICATION_ID, builder.build());
}

From source file:com.stasbar.knowyourself.alarms.AlarmNotifications.java

@TargetApi(Build.VERSION_CODES.N)
private static int getActiveNotificationsCount(Context context, String group) {
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    StatusBarNotification[] notifications = nm.getActiveNotifications();
    int count = 0;
    for (StatusBarNotification statusBarNotification : notifications) {
        final Notification n = statusBarNotification.getNotification();
        if ((n.flags & Notification.FLAG_GROUP_SUMMARY) != Notification.FLAG_GROUP_SUMMARY
                && group.equals(n.getGroup())) {
            count++;/*  ww w . j av  a2  s .  c  o m*/
        }
    }
    return count;
}

From source file:com.androidinspain.deskclock.alarms.AlarmNotifications.java

@TargetApi(Build.VERSION_CODES.N)
private static Notification getActiveGroupSummaryNotification(Context context, String group) {
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    final StatusBarNotification[] notifications = nm.getActiveNotifications();
    for (StatusBarNotification statusBarNotification : notifications) {
        final Notification n = statusBarNotification.getNotification();
        if (isGroupSummary(n) && group.equals(n.getGroup())) {
            return n;
        }//from   w  w  w .  j a va  2 s.co m
    }
    return null;
}

From source file:com.androidinspain.deskclock.alarms.AlarmNotifications.java

/**
 * Method which returns the first active notification for a given group. If a notification was
 * just posted, provide it to make sure it is included as a potential result. If a notification
 * was just canceled, provide the id so that it is not included as a potential result. These
 * extra parameters are needed due to a race condition which exists in
 * {@link NotificationManager#getActiveNotifications()}.
 *
 * @param context Context from which to grab the NotificationManager
 * @param group The group key to query for notifications
 * @param canceledNotificationId The id of the just-canceled notification (-1 if none)
 * @param postedNotification The notification that was just posted
 * @return The first active notification for the group
 *///from   w  w w  .  ja v  a 2  s . co  m
@TargetApi(Build.VERSION_CODES.N)
private static Notification getFirstActiveNotification(Context context, String group,
        int canceledNotificationId, Notification postedNotification) {
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    final StatusBarNotification[] notifications = nm.getActiveNotifications();
    Notification firstActiveNotification = postedNotification;
    for (StatusBarNotification statusBarNotification : notifications) {
        final Notification n = statusBarNotification.getNotification();
        if (!isGroupSummary(n) && group.equals(n.getGroup())
                && statusBarNotification.getId() != canceledNotificationId) {
            if (firstActiveNotification == null
                    || n.getSortKey().compareTo(firstActiveNotification.getSortKey()) < 0) {
                firstActiveNotification = n;
            }
        }
    }
    return firstActiveNotification;
}

From source file:org.smssecure.smssecure.notifications.MessageNotifier.java

private static void cancelOrphanedNotifications(@NonNull Context context, NotificationState notificationState) {
    if (Build.VERSION.SDK_INT >= 23) {
        try {//from w  w  w.  java  2 s  . co  m
            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);
        }
    }
}

From source file:org.smssecure.smssecure.notifications.MessageNotifier.java

private static void cancelActiveNotifications(@NonNull Context context) {
    NotificationManager notifications = ServiceUtil.getNotificationManager(context);
    notifications.cancel(SUMMARY_NOTIFICATION_ID);

    if (Build.VERSION.SDK_INT >= 23) {
        try {//from www  . ja  va2 s .  c om
            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();
        }
    }
}

From source file:com.cyanogenmod.messaging.quickmessage.QuickMessagePopup.java

/**
 * Clears the status bar notification and, optionally, mark all messages as read
 * This is used to clean up when we are done with all qm's
 *
 * @param markAsRead - should remaining qm's be maked as read?
 *//*from ww  w .ja v a2  s  .  c om*/
private void clearNotification(boolean markAsRead) {
    // Dismiss the notification that brought us here.
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    StatusBarNotification[] statusBarNotifications = notificationManager.getActiveNotifications();
    final String packageName = getPackageName();
    for (StatusBarNotification statusBarNotification : statusBarNotifications) {
        if (packageName.equals(statusBarNotification.getPackageName())) {
            notificationManager.cancel(statusBarNotification.getTag(), statusBarNotification.getId());
            break;
        }
    }

    // Mark all contained conversations as seen
    if (markAsRead) {
        markAllMessagesRead();
    }

    // Clear the messages list
    mMessageList.clear();

    if (DEBUG)
        Log.d(LOG_TAG, "clearNotification(): Message list cleared. Size = " + mMessageList.size());
}