Android - NotificationCompat.Builder 堆叠通知与 setGroup(group) 不工作

标签 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);

最佳答案

您没有正确使用通知 ID。

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

from Android Developer

所以在你的情况下,如果你想在你的组中堆叠通知,你需要为每个新通知指定一个新的 id。

关于Android - NotificationCompat.Builder 堆叠通知与 setGroup(group) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25031643/

相关文章:

Android Spotify SDK 登录错误意外 token

android - 使用 AlarmManager 在特定时间显示通知

android - 通知 Intent 不起作用

android - 如何让用户恢复到应用自定义声音?

android - 在 Android 下检索视频的方向信息

javascript - 需要帮助从某些来源播放的视频开发android音频检测

java - Java 中从整型到 char 的隐式类型转换是如何工作的(Java 基础)

android - 从 Mime 类型获取图标,该图标看起来与 Android 中文件应用程序中的图标一模一样

android - 打开 Android 电子市场的通知

java - 如何在 onDestroy 函数中取消通知