Android-NotificationCompat.Builder 使用 setGroup(group) 堆叠通知不起作用

2024-03-27

我想使用 setGroup 堆叠通知(如下所述:https://developer.android.com/training/wearables/notifications/stacks.html https://developer.android.com/training/wearables/notifications/stacks.html) 基本上,我使用 0 作为通知 ID(始终相同)并且builder.setGroup("test_group_key")但新的通知总是会取代之前的通知。 可能是什么问题呢 ?

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:

使用NotificationManagerCompat时似乎存在问题,通知根本不显示。

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

您没有正确使用通知 ID。

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

来自 Android 开发者 http://developer.android.com/training/notify-user/managing.html

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android-NotificationCompat.Builder 使用 setGroup(group) 堆叠通知不起作用 的相关文章

随机推荐