首页 > 解决方案 > 通知仅显示一次,此后不再显示

问题描述

我有一个预定的 FirebaseJob,一旦完成,它会再次安排自己,下一个窗口 ON_ANY_NETWORK。它的工作做得很好,正如预期的那样。我从中调用一项服务,该服务每次都会以未决的意图创建一个新通知。喜欢 :

Intent resultIntent = new Intent(this, MainActivity.class);
    resultIntent.putExtra("NotificationMessage", "NotificationMessage");
    //resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("My App name")
            .setContentText("Content text")
            .setTicker("This is a ticker text")
            .setStyle(new NotificationCompat.BigTextStyle().bigText("This is a long text"))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(resultPendingIntent)
            .setAutoCancel(false)
            .setOngoing(true)
            .setColor(getResources().getColor(android.R.color.holo_red_dark));

    if (notificationManager != null)
    {
        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }

正如我所料,它仅第一次显示通知。我不希望任何用户滑动它,直到应用程序再次打开。一旦从此通知打开应用程序,我将取消通知,例如:

int MY_NOTIFICATION_ID= 234;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(MY_NOTIFICATION_ID);

但是,当我的作业再次开始执行并执行上面显示的用于创建通知的相同代码时,它会执行代码,但通知不会再次显示。董事会成员将不胜感激任何帮助。提前致谢。

标签: javaandroidnotifications

解决方案


这是因为你MY_NOTIFICATION_ID的总是一样的。相反,例如,您可以设置MY_NOTIFICATION_ID为等于System.currentTimeMillis()

int MY_NOTIFICATION_ID= System.currentTimeMillis();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(MY_NOTIFICATION_ID);

推荐阅读