android - 多条消息的更新通知

标签 android android-notifications

下面是我的代码,当新消息到达我的应用程序时生成通知,

代码

 private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        int counter = 0;
        counter++;

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);

        Intent notificationIntent = new Intent(context, MessageActivity.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(counter, notification);

    }

当我收到多条消息时,会有多条通知。

例如

假设我收到 3 条新消息,然后有 3 条单独的通知。但我只想要多条消息的单一通知。当我收到多条消息时,通知应该更新,正如我们在 WhatsApp 中看到的那样。我该怎么做?

最佳答案

如果您有多个消息,例如在 JsonArray 中,您可以遍历数组并为数组中的每个项目创建一个通知。循环中创建的 Notification 可以通过设置相同的 Unique_ID 来更新。如果您想显示一个数字来显示此通知中的消息数量(即未读消息的数字),请创建一个计数器并在循环中将其增加 1。基于目标 Android-SDK 使用例如 NotificationCompat.InboxStyle(需要 android.v4.support 库)或 Notification.InboxStyle 来显示多行通知并使用 InboxStyle.addLine 在循环中添加每个 Arrayitems 的内容。

关于android - 多条消息的更新通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21694419/

相关文章:

java - 如何使用where条件获取Sqlite中的列总和?

android - KitKat ACTION_OPEN_DOCUMENT 不显示三星设备上的文档

android - 特定于区域(而非语言环境)的资源目录

android - 类型NotificationCompat.Builder未定义方法setColor(int)

android - 让我的 Android 应用程序扩展到更大的屏幕

android - 在 SearchView [Inventory App] 中搜索项目时无法滑动删除

android - 使用 NotificationCompat.MediaStyle 和 MediaSessionCompat 从通知中控制我的网络广播播放器

android - 在通知图标中添加数字

android - 通知振动,屏幕锁定时的声音

android - ADB/Shell 命令来管理通知 channel ?