[英]Android: After creating a new notification, the older one is replaced
我想在不取消/删除我的应用程序中以前的通知的情况下创建通知。 这是我创建通知的代码:
private void notification(Context context, String title, String content) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setContentText(content);
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Id allows you to update the notification later on.
mNotificationManager.notify(100, mBuilder.build());
}
您正在为通知使用硬编码 id,当然它会替换旧的。 尝试使用可变 ID 而不是硬编码的 100。
mNotificationManager.notify(100+x, mBuilder.build());
或类似的东西。
使用变量ID的通知,我都面临着这个问题1小时前和使用这种技术来解决这个问题。
val id= Random(System.currentTimeMillis()).nextInt(1000)
mNotificationManager?.notify(id, mBuilder.build())
对于长期解决方案,您可以使用随机方法为您生成整数变量并在通知中调用它。
mNotificationManager.notify(createRandomCode(7), mBuilder.build());
public int createRandomCode(int codeLength) {
char[] chars = "1234567890".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new SecureRandom();
for (int i = 0; i < codeLength; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
return Integer.parseInt(sb.toString());
}
在创建 PendingIntent 对象时,我们调用 PendingIntent.getActivity(mContext, requestCode , intent, PendingIntent.FLAG_UPDATE_CURRENT);
所以这里使用下面的代码来生成 PendingIntent
Random objRandom = new Random();
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
objRandom.nextInt(100),
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.