android - 如何防止 Android 通知覆盖自己?

标签 android android-notifications

我正在使用 XMPP (smack) 创建消息传递应用程序,并且在收到新消息时发送通知。问题是,如果我收到来自两个不同用户的消息,我只能看到最后一条通知。我该如何改变它?这是我的代码。

Intent thisIntent = new Intent(mApplicationContext, ChatActivity.class);
thisIntent.putExtra("EXTRA_CONTACT_JID",contactJid);
PendingIntent contentIntent = PendingIntent.getActivity(mApplicationContext, 0, thisIntent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder b = new NotificationCompat.Builder(mApplicationContext);

b.setAutoCancel(true)
        .setDefaults(Notification.DEFAULT_ALL)
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.drawable.fab_bg_mini)
        .setTicker("Hearty365")
        .setContentTitle("New message")
        .setContentText(" You received a new message from " + contactJid)
        .setContentIntent(contentIntent)
        .setContentInfo("Info");
if(!ChatActivity.active){
    b.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND);
}

NotificationManager notificationManager = (NotificationManager) mApplicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());

如您所见,我添加了一个对我来说很重要的额外 contactJid。我需要以这样一种方式设置它,如果用户单击一个通知,它的 contactJid 将是这个,如果另一个它的 contactJid 将是另一个。

最佳答案

notificationManager.notify(1, b.build()); 是您的问题 - 您需要为此通知提供唯一标识符,as per the documentation :

If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.

您为每个通知提供常量 1,而不是唯一 ID。我建议使用联系人 JID 的散列(我假设它是一个字符串):

notificationManager.notify(contactJid.hashCode(), b.build());

关于android - 如何防止 Android 通知覆盖自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41338535/

相关文章:

android - 将应用程序传递给 AndroidViewModel

android - `react-native-camera` 返回一个 data.uri 但无法访问图像(没有这样的文件或目录)

android - 如何添加通知计数器 Android

安卓 GCM : Not getting registration token on onCreate() method

javascript - 文本框焦点在使用 JavaScript 和 PhoneGap 的 Android 设备中不起作用

php - 在MySql中插入phonegap数据

android - 在android studio中使用org.apache.http.client

android - 确定触摸通知图标的作用

android - 从 SQLite DB 设置 android 通知

android - 在sony smartwatch 2中生成动态列表