在创建新通知时,使用相同的通知ID并设置新内容,这样旧的通知将被更新而不是被替换。
示例代码如下:
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String channelId = "channelId"; int notificationId = 1;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Title") .setContentText("Content");
notificationManager.notify(notificationId, builder.build());
// 创建新通知,使用相同的notificationId替换旧通知 NotificationCompat.Builder builderNew = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("New Title") .setContentText("New Content");
notificationManager.notify(notificationId, builderNew.build());