【问题标题】:Update Notification for multiple messages多条消息的更新通知
【发布时间】:2014-02-11 06:10:04
【问题描述】:

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

代码

 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 中看到的那样。我该怎么做?

【问题讨论】:

  • 为您的通知设置唯一 ID。
  • @MD:你的意思是在这一行中 notificationManager.notify(counter, notification); ???
  • 您的计数器值每次都会发生变化,但您可以使用唯一 ID 来解决此问题。我的意思是唯一的 int 值
  • 你是 f9 哥们,但我希望上一条消息应该在那里......
  • 顺便说一句,你的问题很好。祝你好运......

标签: android android-notifications


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 2020-04-15
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多