下面是我的代码,当新消息到达我的应用程序时生成通知,
代码
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/