Android:创建新通知后,将替换旧通知

M.V*_*eli 13 notifications android notify

我想在不取消/删除我的应用程序的先前通知的情况下创建通知.这是我创建通知的代码:

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());
}
Run Code Online (Sandbox Code Playgroud)

Jox*_*aex 26

您正在使用硬编码的ID进行通知,当然它将替换旧的ID.尝试使用变量ID而不是硬编码100.

mNotificationManager.notify(100+x, mBuilder.build());
Run Code Online (Sandbox Code Playgroud)

或类似的东西.


Mah*_*rok 8

使用变量 id进行通知,我1 小时前 就遇到过这个问题,并使用这种技术来克服这个问题。

        val id= Random(System.currentTimeMillis()).nextInt(1000)
        mNotificationManager?.notify(id, mBuilder.build())
Run Code Online (Sandbox Code Playgroud)