Android - NotificationCompat.Builder stacking notifications with setGroup(group) not working

非 Y 不嫁゛ 提交于 2019-12-08 16:53:30

问题


I want to stack notifications using setGroup (as described here: https://developer.android.com/training/wearables/notifications/stacks.html) Basically, I use 0 as notification id (always the same) and builder.setGroup("test_group_key") but a new notification always replaces the previous one. What could be the problem ?

Code:

public BasicNotifier(Context context) {
    super(context);
    notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    mBuilder = new NotificationCompat.Builder(context)
        .setSmallIcon(R.drawable.ic_launcher)
        .setSound(alarmSound)
        .setAutoCancel(true);

    stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(getParentActivityClass());

}

public void showNotification(String title, String text, Intent intent, Class cls) {
    if (text.length() > 190)
        text = text.substring(0, 189) + "...";

    mBuilder.setTicker(text).setContentText(text).setContentTitle(title);

    Intent notificationIntent = intent == null ? new Intent() : new Intent(intent);
    notificationIntent.setClass(getContext(), cls);
    stackBuilder.addNextIntent(notificationIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mBuilder.setGroup("test_group_key");

    Notification notif = mBuilder.build();
    notif.flags |= Notification.FLAG_AUTO_CANCEL;

    notifManager.notify(replaceOnNew ? 0 : nextId++, notif); // replaceOnNew
                                                                // is "true"

    Log.i(TAG, "Notification shown: " + nextId + " = " + title);
}

EDIT:

It seams there is a problem when using NotificationManagerCompat, the notifications are not being displayed at all.

  NotificationManagerCompat notificationManager =
            NotificationManagerCompat.from(getContext());
  notificationManager.notify(id, notif);

回答1:


You don't use notification id correctly.

"To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(ID, notification). To update this notification once you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you used previously."

from Android Developer

So in your case, if you want to stack notification in your group, you need to specify a new id for each new notification.



来源:https://stackoverflow.com/questions/25031643/android-notificationcompat-builder-stacking-notifications-with-setgroupgroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!