Android - NotificationCompat.Builder堆叠通知与setGroup(组)无法正常工作

时间:2014-07-30 08:01:34

标签: android android-notifications

我想使用setGroup堆栈通知(如下所述:https://developer.android.com/training/wearables/notifications/stacks.html) 基本上,我使用0作为通知ID(始终相同)和builder.setGroup("test_group_key")但是新通知总是替换前一个通知。 可能是什么问题?

代码:

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);
}

编辑:

使用NotificationManagerCompat时出现问题,根本没有显示通知。

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

1 个答案:

答案 0 :(得分:4)

您没有正确使用通知ID。

“要设置通知以便更新,请通过调用NotificationManager.notify(ID,通知)向通知ID发出通知。要在发出通知后更新此通知,请更新或创建NotificationCompat.Builder对象,从中构建Notification对象,并使用您之前使用的相同ID发出通知。“

from Android Developer

因此,在您的情况下,如果您要在群组中堆叠通知,则需要为每个新通知指定新ID。