Java Code Examples for android.service.notification.StatusBarNotification#getNotification()

The following examples show how to use android.service.notification.StatusBarNotification#getNotification() . 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: NotificationRecord.java    From android_9.0.0_r45 with Apache License 2.0 7 votes vote down vote up
public NotificationRecord(Context context, StatusBarNotification sbn,
        NotificationChannel channel) {
    this.sbn = sbn;
    mTargetSdkVersion = LocalServices.getService(PackageManagerInternal.class)
            .getPackageTargetSdkVersion(sbn.getPackageName());
    mAm = ActivityManager.getService();
    mOriginalFlags = sbn.getNotification().flags;
    mRankingTimeMs = calculateRankingTimeMs(0L);
    mCreationTimeMs = sbn.getPostTime();
    mUpdateTimeMs = mCreationTimeMs;
    mInterruptionTimeMs = mCreationTimeMs;
    mContext = context;
    stats = new NotificationUsageStats.SingleNotificationStats();
    mChannel = channel;
    mPreChannelsNotification = isPreChannelsNotification();
    mSound = calculateSound();
    mVibration = calculateVibration();
    mAttributes = calculateAttributes();
    mImportance = calculateImportance();
    mLight = calculateLights();
    mAdjustments = new ArrayList<>();
    mStats = new NotificationStats();
    calculateUserSentiment();
    calculateGrantableUris();
}
 
Example 2
Source File: Notification.java    From an2linuxclient with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.KITKAT)
private void extractMessage(StatusBarNotification sbn) {
    Bundle extras = sbn.getNotification().extras;

    String contentText = "";
    String subText = "";
    CharSequence temp = extras.getCharSequence(android.app.Notification.EXTRA_TEXT);
    if (temp != null){
        contentText = temp.toString();
    }
    temp = extras.getCharSequence(android.app.Notification.EXTRA_SUB_TEXT);
    if (temp != null){
        subText = temp.toString();
    }

    message = "";
    if (!contentText.equals("")) message += contentText;
    if (!subText.equals("")) message += "\n" + subText;
    message = message.replace("\n\n", "\n").trim();
    if (message.length() > ns.getMessageMax()){
        message = message.substring(0, ns.getMessageMax()) + "…";
    }
}
 
Example 3
Source File: NotificationHelper.java    From NotificationPeekPort with Apache License 2.0 6 votes vote down vote up
public static boolean shouldDisplayNotification(StatusBarNotification oldNotif,
                                                StatusBarNotification newNotif) {
    // First check for ticker text, if they are different, some other parameters will be
    // checked to determine if we should show the notification.
    CharSequence oldTickerText = oldNotif.getNotification().tickerText;
    CharSequence newTickerText = newNotif.getNotification().tickerText;
    if (newTickerText == null ? oldTickerText == null : newTickerText.equals(oldTickerText)) {
        // If old notification title isn't null, show notification if
        // new notification title is different. If it is null, show notification
        // if the new one isn't.
        String oldNotificationText = getNotificationTitle(oldNotif);
        String newNotificationText = getNotificationTitle(newNotif);
        if (newNotificationText == null ? oldNotificationText != null : !newNotificationText
                .equals(oldNotificationText)) {
            return true;
        }

        // Last chance, check when the notifications were posted. If times
        // are equal, we shouldn't display the new notification.
        if (oldNotif.getNotification().when != newNotif.getNotification().when) {
            return true;
        }
        return false;
    }
    return true;
}
 
Example 4
Source File: Notification.java    From an2linuxclient with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.KITKAT)
private void extractMessage(StatusBarNotification sbn) {
    Bundle extras = sbn.getNotification().extras;

    String contentText = "";
    String subText = "";
    CharSequence temp = extras.getCharSequence(android.app.Notification.EXTRA_TEXT);
    if (temp != null){
        contentText = temp.toString();
    }
    temp = extras.getCharSequence(android.app.Notification.EXTRA_SUB_TEXT);
    if (temp != null){
        subText = temp.toString();
    }

    message = "";
    if (!contentText.equals("")) message += contentText;
    if (!subText.equals("")) message += "\n" + subText;
    message = message.replace("\n\n", "\n").trim();
    if (message.length() > ns.getMessageMax()){
        message = message.substring(0, ns.getMessageMax()) + "…";
    }
}
 
Example 5
Source File: NotificationCountService.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
private void broadcastNotificationCount() {
    int count = 0;

    StatusBarNotification[] notifications;
    try {
        notifications = getActiveNotifications();
    } catch (SecurityException e) {
        notifications = new StatusBarNotification[0];
    }

    for(StatusBarNotification notification : notifications) {
        if((notification.getNotification().flags & NotificationCompat.FLAG_GROUP_SUMMARY) == 0
            && notification.isClearable()) count++;
    }

    broadcastNotificationCount(count);
}
 
Example 6
Source File: NotificationHelper.java    From NotificationPeekPort with Apache License 2.0 5 votes vote down vote up
public static String getNotificationContent(StatusBarNotification n) {
    String content = getNotificationTextLines(n);

    if (content.length() == 0) {
        content = getNotificationText(n, Notification.EXTRA_TEXT);
    }

    if (content == null) {
        return n.getNotification().tickerText == null ? "" : n.getNotification().tickerText
                .toString();
    }
    return content;
}
 
Example 7
Source File: NotificationListener.java    From openlauncher with Apache License 2.0 5 votes vote down vote up
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    // Some apps do not track total notifications in their StatusBarNotification; given this
    // is an onNotificationPosted, ensure we have a minimum count to display the badge, otherwise
    // it will be removed which is counter-intuitive.
    int notificationCount = sbn.getNotification().number;
    if (notificationCount == 0) {
        notificationCount = 1;
    }
    processCallback(sbn.getPackageName(), notificationCount);
 }
 
Example 8
Source File: ModLedControl.java    From GravityBox with Apache License 2.0 5 votes vote down vote up
private static boolean isHeadsUpAllowed(StatusBarNotification sbn, Context context) {
    if (context == null) return false;

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    Notification n = sbn.getNotification();
    return (pm.isInteractive() &&
            keyguardAllowsHeadsUp(context) &&
            (!sbn.isOngoing() || n.fullScreenIntent != null || (n.extras.getInt("headsup", 0) != 0)));
}
 
Example 9
Source File: NotificationService.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onNotificationPosted(StatusBarNotification sbn) {

    if (AndroidUtils.isVersionKitKat()) {
        String pack = sbn.getPackageName();
        String ticker = getString(sbn.getNotification().tickerText);
        Bundle extras = sbn.getNotification().extras;
        String title = "";
        String text = "";
        if (extras != null) {
            title = extras.getString("android.title");
            text = getString(extras.getCharSequence("android.text"));
        }

        /*
        Log.i("Package", pack);
        Log.i("Ticker", ticker);
        Log.i("Title", title);
        Log.i("Text", text);
        */

        Intent msgrcv = new Intent("Msg");
        msgrcv.putExtra("package", pack);
        msgrcv.putExtra("ticker", ticker);
        msgrcv.putExtra("title", title);
        msgrcv.putExtra("text", text);
        LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
    }
}
 
Example 10
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 11
Source File: NotificationListenerService.java    From NotificationBox with MIT License 5 votes vote down vote up
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    super.onNotificationPosted(sbn);
    Log.d(TAG, "onNotificationPosted");

    Notification notification = sbn.getNotification();

    String packageName = sbn.getPackageName();
    long time = sbn.getPostTime();
    String title = notification.extras.getString(Notification.EXTRA_TITLE);
    String text = notification.extras.getString(Notification.EXTRA_TEXT);

    DbUtils.saveNotification(new NotificationInfo(packageName, title, text, time));
    List<AppInfo> blackList = DbUtils.getApp();

    for (AppInfo app : blackList) {
        if (packageName.equals(app.getPackageName())) {
            Log.d(TAG, packageName + " 拦截:" + title + ": " + text);

            if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
                cancelNotification(sbn.getKey());
            } else {
                cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
            }

            if (SettingUtils.getInstance().isNotify()) {
                createNotification(app.getAppName(), packageName, title, text);
            }
        }
    }
}
 
Example 12
Source File: NotificationListener.java    From flutter-plugins with MIT License 5 votes vote down vote up
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    // Retrieve package name to set as title.
    String packageName = sbn.getPackageName();
    // Retrieve extra object from notification to extract payload.
    Bundle extras = sbn.getNotification().extras;
    String packageMessage = extras.getCharSequence(Notification.EXTRA_TEXT).toString();
    // Pass data from one activity to another.
    Intent intent = new Intent(NOTIFICATION_INTENT);
    intent.putExtra(NOTIFICATION_PACKAGE_NAME, packageName);
    intent.putExtra(NOTIFICATION_PACKAGE_MESSAGE, packageMessage);
    sendBroadcast(intent);
}
 
Example 13
Source File: DownloadNotificationService.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Checks to see if the summary notification is alone and, if so, hides it.  If the summary
 * notification thinks it's in the foreground, this will start the service with the goal of
 * shutting it down.  That is because if the service is in the foreground it's not possible to
 * stop it through the notification manager.
 * @param removedNotificationId The id of the notification that was just removed or {@code -1}
 *                              if this does not apply.
 */
@TargetApi(Build.VERSION_CODES.M)
public static void hideDanglingSummaryNotification(Context context, int removedNotificationId) {
    if (!useForegroundService()) return;

    NotificationManager manager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (hasDownloadNotifications(manager, removedNotificationId)) return;

    StatusBarNotification summary = getSummaryNotification(manager);
    if (summary == null) return;

    boolean isForeground =
            (summary.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE) != 0;

    if (BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER)
                    .isStartupSuccessfullyCompleted()) {
        RecordHistogram.recordBooleanHistogram(
                "MobileDownload.Notification.FixingSummaryLeak", isForeground);
    }

    if (isForeground) {
        // If it is a foreground notification, we are in a bad state.  We don't have any
        // other download notifications, but we can't close the summary.  Try to start
        // up the service and quit through that path?
        startDownloadNotificationService(context, new Intent(ACTION_DOWNLOAD_FAIL_SAFE));
    } else {
        manager.cancel(NotificationConstants.NOTIFICATION_ID_DOWNLOAD_SUMMARY);
    }
}
 
Example 14
Source File: NotificationPeek.java    From NotificationPeekPort with Apache License 2.0 5 votes vote down vote up
private boolean shouldDisplayNotification(StatusBarNotification n) {
    if (n.getNotification().priority < Notification.PRIORITY_DEFAULT) {
        return false;
    }
    for (StatusBarNotification shown : mShownNotifications) {
        if (NotificationHelper.getContentDescription(n)
                .equals(NotificationHelper.getContentDescription(shown))) {
            return NotificationHelper.shouldDisplayNotification(shown, n);
        }
    }
    return true;
}
 
Example 15
Source File: NotificationHelper.java    From NotificationPeekPort with Apache License 2.0 5 votes vote down vote up
/**
 * Get text from notification with specific field.
 *
 * @param n     StatusBarNotification object.
 * @param field StatusBarNotification extra field.
 * @return Notification text.
 */
public static String getNotificationText(StatusBarNotification n, String field) {
    String text = null;
    if (n != null) {
        Notification notification = n.getNotification();
        Bundle extras = notification.extras;
        CharSequence chars = extras.getCharSequence(field);
        text = chars != null ? chars.toString() : null;
    }
    return text;
}
 
Example 16
Source File: DownloadNotificationService.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Check all current notifications and hide the summary notification if we have no downloads
 * notifications left.  On Android if the user swipes away the last download notification the
 * summary will be dismissed.  But if the last downloads notification is dismissed via
 * {@link NotificationManager#cancel(int)}, the summary will remain, so we need to check and
 * manually remove it ourselves.
 * @param notificationIdToIgnore Canceling a notification and querying for the current list of
 *                               active notifications isn't synchronous.  Pass a notification id
 *                               here if there is a notification that should be assumed gone.
 *                               Or pass -1 if no notification fits that criteria.
 */
@TargetApi(Build.VERSION_CODES.M)
boolean hideSummaryNotificationIfNecessary(int notificationIdToIgnore) {
    if (!useForegroundService()) return false;
    if (mDownloadsInProgress.size() > 0) return false;

    if (hasDownloadNotificationsInternal(notificationIdToIgnore)) return false;

    StatusBarNotification notification = getSummaryNotification(mNotificationManager);
    if (notification != null) {
        // We have a valid summary notification, but how we dismiss it depends on whether or not
        // it is currently bound to this service via startForeground(...).
        if ((notification.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE)
                != 0) {
            // If we are a foreground service and we are hiding the notification, we have no
            // other downloads notifications showing, so we need to remove the notification and
            // unregister it from this service at the same time.
            stopForegroundInternal(true);
        } else {
            // If we are not a foreground service, remove the notification via the
            // NotificationManager.  The notification is not bound to this service, so any call
            // to stopForeground() won't affect the notification.
            cancelSummaryNotification();
        }
    } else {
        // If we don't have a valid summary, just guarantee that we aren't in the foreground for
        // safety.  Still try to remove the summary notification to make sure it's gone.  This
        // is because querying for it might fail if we have just recently started up and began
        // showing it.  This might leave us in a bad state if the cancel request fails inside
        // the framework.
        // TODO(dtrainor): Add a way to attempt to automatically clean up the notification
        // shortly after this.
        stopForegroundInternal(true);
    }

    // Stop the service which should start the destruction process.  At this point we should be
    // a background service.  We might not be unbound from any clients.  When they unbind we
    // will shut down.  That is okay because they will only unbind from us when they are ok with
    // us going away (e.g. we shouldn't be unbound while in the foreground).
    stopSelf();
    return true;
}
 
Example 17
Source File: NotificationKeyData.java    From LaunchEnr with GNU General Public License v3.0 4 votes vote down vote up
public static NotificationKeyData fromNotification(StatusBarNotification sbn) {
    Notification notif = sbn.getNotification();
    return new NotificationKeyData(sbn.getKey(), AndroidVersion.isAtLeastOreo() ? notif.getShortcutId() : null, notif.number);
}
 
Example 18
Source File: NotificationListenerService.java    From GoFIT_SDK_Android with Apache License 2.0 4 votes vote down vote up
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    super.onNotificationPosted(sbn);
    AppContract.emIncomingMessageType type = AppContract.emIncomingMessageType.Default;
    for (int i = 0; i < packageList.length; i++) {
        if (packageList[i].equals(sbn.getPackageName())) {
            type = AppContract.emIncomingMessageType.values()[i];
            break;
        }
    }

    String message = "";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        message = getNotificationSinceKITKAT(sbn.getNotification().extras);
        message = message.replace(":", ":");
    }

    if (message.length() == 0) {
        if (sbn.getNotification().tickerText != null) {
            message = sbn.getNotification().tickerText.toString();
            if (message.length() == 0) {
                try {
                    RemoteViews rv = sbn.getNotification().tickerView;
                    for (Field field : rv.getClass().getDeclaredFields()) {
                        field.setAccessible(true);

                        if (field.getName().equals("mActions")) {
                            ArrayList<Objects> things = (ArrayList<Objects>) field.get(rv);
                            for (Objects object : things) {
                                for (Field innerField : object.getClass().getDeclaredFields()) {
                                    if (innerField.getName().equals("value")) {
                                        Object innerObj = innerField.get(object);
                                        if (innerObj instanceof String || innerObj instanceof SpannableString) {
                                            if (message.length() > 0) {
                                                message += ":";
                                            }

                                            message += innerField.get(object).toString();
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            message = message.replace(":", ":");
        } else {
            message = type == AppContract.emIncomingMessageType.Default ? "New Message!" : getApplicationName(sbn.getPackageName());
        }
    }

    if (message == null) {
        message = "";
    }
    long postTime = sbn.getPostTime();
    if (!(type == lastType && message.equals(lastMessage) && (postTime - lastPostTime < 3000))) {
        doSendIncomingEventToDevice(type, message, sbn.getPackageName());
        lastType = type;
        lastMessage = message;
        lastPostTime = postTime;
    }
}
 
Example 19
Source File: NotificationPeekActivity.java    From NotificationPeekPort with Apache License 2.0 4 votes vote down vote up
/**
 * Update notification views upon each swipe, moving the next latest notification to 'Current
 * Notification' spot, and remove it from the small icon container.
 *
 * @param description Description of the StatusBarNotification we just swiped.
 * @return True if the update is successful, i.e there is more than one unread notification.
 * False if the notification we just swipe away is the last unread notification.
 */
private boolean updateNotification(String description) {

    int currentNotificationIdex =
            getCurrentNotificationIndex(mNotificationsContainer, description);

    // Remove the current notification from container.
    mNotificationsContainer.removeViewAt(currentNotificationIdex);

    int nextNotificationIndex = mNotificationsContainer.getChildCount() - 1;

    // We have more than one unread notification.
    if (nextNotificationIndex >= 0) {
        StatusBarNotification nextNotification = (StatusBarNotification) mNotificationsContainer
                .getChildAt(nextNotificationIndex).getTag();

        if (nextNotification.getNotification().largeIcon != null) {
            mNotificationIcon.setImageDrawable(NotificationPeekViewUtils
                    .getRoundedShape(getResources(),
                            nextNotification.getNotification().largeIcon));
        } else {
            mNotificationIcon.setImageDrawable(
                    NotificationPeekViewUtils.getIconFromResource(this, nextNotification));
        }

        mNotificationText.setText(
                NotificationPeekViewUtils.getNotificationDisplayText(this, nextNotification));

        // Animate back icon and text.
        mNotificationView.setTranslationX(0);
        mNotificationView.animate().alpha(1f).start();

        // Set new tag.
        mNotificationView.setTag(nextNotification);
        mPeek.getNotificationHub().setCurrentNotification(nextNotification);

        final PendingIntent contentIntent = nextNotification.getNotification().contentIntent;
        if (contentIntent != null) {
            NotificationClicker mNotificationClicker =
                    new NotificationClicker(this, contentIntent, mPeek);
            mNotificationIcon.setOnClickListener(mNotificationClicker);
        } else {
            mNotificationIcon.setOnClickListener(null);
        }

        if (nextNotificationIndex == 0) {
            // As we already moved the next notification to 'Current Notification' spot, we need
            // to hide it too if there is only one unread notification left.
            mNotificationsContainer.getChildAt(nextNotificationIndex).setVisibility(View.GONE);
        } else {
            // Otherwise, highlight that icon.
            mNotificationsContainer.getChildAt(nextNotificationIndex).setAlpha(1);
        }
        // Recover TextView alpha, because we will still have notification(s) to show.
        mPeek.updateNotificationTextAlpha(1);

        return true;
    }

    // The only unread notification is swiped away.
    return false;
}
 
Example 20
Source File: NotificationListener.java    From MiPushFramework with GNU General Public License v3.0 4 votes vote down vote up
private NotificationBarInfoItem buildItem(int i, StatusBarNotification statusBarNotification) {
    int i2 = 0;
    if (statusBarNotification == null || statusBarNotification.getPackageName() == null) {
        return null;
    }
    NotificationBarInfoItem notificationBarInfoItem = new NotificationBarInfoItem();
    Notification notification = statusBarNotification.getNotification();
    if (notification == null) {
        return null;
    }
    notificationBarInfoItem.setType(i);
    notificationBarInfoItem.setPackageName(statusBarNotification.getPackageName());
    notificationBarInfoItem.setNotifyId(statusBarNotification.getId());
    if (notification.extras != null) {
        notificationBarInfoItem.setTitle(notification.extras.getString("android.title", ""));
        notificationBarInfoItem.setContent(notification.extras.getString("android.text", ""));
    }
    notificationBarInfoItem.setCustomLayoutIsSet(notification.contentView != null);
    Object callMethod = JavaCalls.callMethod(notification.contentIntent, "getIntent", new Object[0]);
    if (callMethod != null && (callMethod instanceof Intent)) {
        notificationBarInfoItem.setIntentUri(((Intent) callMethod).toUri(1));
    }
    notificationBarInfoItem.setArrivedTime(notification.when / 1000);
    notificationBarInfoItem.setRemovedTime(i == 2 ? System.currentTimeMillis() / 1000 : -1);
    notificationBarInfoItem.setFlags(notification.flags);
    notificationBarInfoItem.setPriority(notification.priority);
    if (notification.actions != null) {
        i2 = notification.actions.length;
    }
    notificationBarInfoItem.setActions(i2);
    notificationBarInfoItem.setDefaults(notification.defaults);
    if (VERSION.SDK_INT < 21) {
        return notificationBarInfoItem;
    }
    try {
        notificationBarInfoItem.setVisibility(((Integer) JavaCalls.getField(notification, "visibility")).intValue());
        notificationBarInfoItem.setCategory((String) JavaCalls.getField(notification, "category"));
        notificationBarInfoItem.setColor(((Integer) JavaCalls.getField(notification, "color")).intValue());
        return notificationBarInfoItem;
    } catch (Exception e) {
        return notificationBarInfoItem;
    }
}