如何将多个通知显示为一个组?

时间:2016-05-31 07:21:27

标签: android notifications android-notifications

这是我的通知代码。它每次都会生成一个新通知

Random random = new Random();
int m = random.nextInt(9999 - 1000);    
NotificationCompat.Builder mBuilder =new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.quemark1)
                    .setContentTitle("New Message")
                    .setContentText(message)
Intent intent = new Intent(this, ActivityMain.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(ActivityMain.class);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager)     context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
mNotificationManager.notify(m, mBuilder.build());

here is the output of my code

4 个答案:

答案 0 :(得分:6)

在为手持设备创建通知时,您应始终将类似的通知聚合到一个摘要通知中。

选中它会显示如何构建堆栈通知。

private void sendStackNotificationIfNeeded(RemoteNotification remoteNotification) {
    // only run this code if the device is running 23 or better
    if (Build.VERSION.SDK_INT >= 23) {
        ArrayList<StatusBarNotification> groupedNotifications = new ArrayList<>();

        // step through all the active StatusBarNotifications and
        for (StatusBarNotification sbn : getNotificationManagerService().getActiveNotifications()) {
            // add any previously sent notifications with a group that matches our RemoteNotification
            // and exclude any previously sent stack notifications
            if (remoteNotification.getUserNotificationGroup() != null &&
                    remoteNotification.getUserNotificationGroup().equals(sbn.getNotification().getGroup()) &&
                    sbn.getId() != RemoteNotification.TYPE_STACK) {
                groupedNotifications.add(sbn);
            }
        }

        // since we assume the most recent notification was delivered just prior to calling this method,
        // we check that previous notifications in the group include at least 2 notifications
        if (groupedNotifications.size() > 1) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            // use convenience methods on our RemoteNotification wrapper to create a title
            builder.setContentTitle(String.format("%s: %s", remoteNotification.getAppName(), remoteNotification.getErrorName()))
                    .setContentText(String.format("%d new activities", groupedNotifications.size()));

            // for every previously sent notification that met our above requirements,
            // add a new line containing its title to the inbox style notification extender
            NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle();
            {
                for (StatusBarNotification activeSbn : groupedNotifications) {
                    String stackNotificationLine = (String)activeSbn.getNotification().extras.get(NotificationCompat.EXTRA_TITLE);
                    if (stackNotificationLine != null) {
                        inbox.addLine(stackNotificationLine);
                    }
                }

                // the summary text will appear at the bottom of the expanded stack notification
                // we just display the same thing from above (don't forget to use string
                // resource formats!)
                inbox.setSummaryText(String.format("%d new activities", groupedNotifications.size()));
            }
            builder.setStyle(inbox);

            // make sure that our group is set the same as our most recent RemoteNotification
            // and choose to make it the group summary.
            // when this option is set to true, all previously sent/active notifications
            // in the same group will be hidden in favor of the notifcation we are creating
            builder.setGroup(remoteNotification.getUserNotificationGroup())
                .setGroupSummary(true);

            // if the user taps the notification, it should disappear after firing its content intent
            // and we set the priority to high to avoid Doze from delaying our notifications
            builder.setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

            // create a unique PendingIntent using an integer request code.
            final int requestCode = (int)System.currentTimeMillis() / 1000;
            builder.setContentIntent(PendingIntent.getActivity(this, requestCode, DetailActivity.createIntent(this), PendingIntent.FLAG_ONE_SHOT));

            Notification stackNotification = builder.build();
            stackNotification.defaults = Notification.DEFAULT_ALL;

            // finally, deliver the notification using the group identifier as the Tag
            // and the TYPE_STACK which will cause any previously sent stack notifications
            // for this group to be updated with the contents of this built summary notification
            getNotificationManagerService().notify(remoteNotification.getUserNotificationGroup(), RemoteNotification.TYPE_STACK, stackNotification);
        }
    }
}

答案 1 :(得分:5)

它会生成包含Gmail等多条消息的通知

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.quemark1)
                    .setContentTitle("Title")
                    .setContentText("New Message received");
            NotificationCompat.InboxStyle inboxStyle =
                    new NotificationCompat.InboxStyle();

            inboxStyle.setBigContentTitle("doUdo");

           // Add your All messages here or use Loop to generate messages

                inboxStyle.addLine("Messgare 1");
                inboxStyle.addLine("Messgare 2");
                          .
                          .
                inboxStyle.addLine("Messgare n");


            mBuilder.setStyle(inboxStyle);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

            stackBuilder.addNextIntent(intent);

            PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            mBuilder.setContentIntent(pIntent);

            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
            mBuilder.setAutoCancel(true);
            mNotificationManager.notify(0, mBuilder.build());

答案 2 :(得分:0)

    String GROUP_KEY_WORK_EMAIL = "com.android.example.WORK_EMAIL";

Notification newMessageNotification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
        .setSmallIcon(R.drawable.new_mail)
        .setContentTitle(emailObject.getSenderName())
        .setContentText(emailObject.getSubject())
        .setLargeIcon(emailObject.getSenderAvatar())
        .setGroup(GROUP_KEY_WORK_EMAIL)
        .build();
By default, notifications are sorted according to when they were posted, but you can change order by calling setSortKey().

If alerts for a notification's group should be handled by a different notification, call setGroupAlertBehavior(). For example, if you want only the summary of your group to make noise, all children in the group should have the group alert behavior GROUP_ALERT_SUMMARY. The other options are GROUP_ALERT_ALL and GROUP_ALERT_CHILDREN.

Set a group summary
On Android 7.0 (API level 24) and higher, the system automatically builds a summary for your group using snippets of text from each notification. The user can expand this notification to see each separate notification, as shown in figure 1. To support older versions, which cannot show a nested group of notifications, you must create an extra notification that acts as the summary. This appears as the only notification and the system hides all the others. So this summary should include a snippet from all the other notifications, which the user can tap to open your app.

Note: The behavior of the group summary may vary on some device types such as wearables. To ensure the best experience on all devices and versions, always include a group summary when you create a group.
To add a group summary, proceed as follows:

Create a new notification with a description of the group—often best done with the inbox-style notification.
Add the summary notification to the group by calling setGroup().
Specify that it should be used as the group summary by calling setGroupSummary(true).
For example:

//use constant ID for notification used as group summary
int SUMMARY_ID = 0;
String GROUP_KEY_WORK_EMAIL = "com.android.example.WORK_EMAIL";

Notification newMessageNotification1 =
    new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notify_email_status)
        .setContentTitle(emailObject1.getSummary())
        .setContentText("You will not believe...")
        .setGroup(GROUP_KEY_WORK_EMAIL)
        .build();

Notification newMessageNotification2 =
    new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notify_email_status)
        .setContentTitle(emailObject2.getSummary())
        .setContentText("Please join us to celebrate the...")
        .setGroup(GROUP_KEY_WORK_EMAIL)
        .build();

Notification summaryNotification =
    new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
        .setContentTitle(emailObject.getSummary())
        //set content text to support devices running API level < 24
        .setContentText("Two new messages")
        .setSmallIcon(R.drawable.ic_notify_summary_status)
        //build summary info into InboxStyle template
        .setStyle(new NotificationCompat.InboxStyle()
                .addLine("Alex Faarborg  Check this out")
                .addLine("Jeff Chang    Launch Party")
                .setBigContentTitle("2 new messages")
                .setSummaryText("janedoe@example.com"))
        //specify which group this notification belongs to
        .setGroup(GROUP_KEY_WORK_EMAIL)
        //set this notification as the summary for the group
        .setGroupSummary(true)
        .build();

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(emailNotificationId1, newMessageNotification1);
notificationManager.notify(emailNotificationId2, newMessageNotification2);
notificationManager.notify(SUMMARY_ID, summaryNotification);

摘要通知ID应该保持不变,以便仅发布一次,因此,如果摘要信息发生更改(以后添加到组中将导致更新现有摘要),则可以稍后对其进行更新。

答案 3 :(得分:-1)

使用以下代码为您的通知管理员提供代码,并在收到新通知时递增计数。

mNotificationManager.notify(count, mBuilder.build());