【问题标题】:Notification startForeground() not working the second time通知 startForeground() 第二次不工作
【发布时间】:2020-01-24 06:33:29
【问题描述】:

我正在使用服务类创建通知。它适用于以下 android O,但对于更高版本,通知是第一次显示,如果我尝试第二次显示它,它不会显示。以下是我的代码:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Log.e("inside here", "inside ");
        NotificationManager manager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL, PRIMARY_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        manager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(service, PRIMARY_CHANNEL)
            .setAutoCancel(false)
            .setContentTitle(strLiveBroadcast)
            .setContentText(strAppName)
            .setLargeIcon(largeIcon)
            .setContentIntent(pendingIntent)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setSmallIcon(android.R.drawable.stat_sys_headset)
            .addAction(icon, "pause", action)
            .addAction(R.drawable.ic_stop_white, "stop", stopAction)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setWhen(System.currentTimeMillis())
            .setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
                    .setMediaSession(service.getMediaSession().getSessionToken())
                    .setShowActionsInCompactView(0, 1)
                    .setShowCancelButton(true)
                    .setCancelButtonIntent(stopAction));

    service.startForeground(NOTIFICATION_ID, builder.build());

这在较低版本中完全可以正常工作。

【问题讨论】:

  • 请发此方法代码:onMessageReceived
  • 它第一次在更高版本中也可以工作,但第二次就不行了。
  • @Ali 我不清楚你想说什么。

标签: android android-notifications notificationmanager


【解决方案1】:

startForeground() 不适用于通知如果 NOTIFICATION_ID 参数设置为 0 或者您需要在每次调用时添加 Random Id 逻辑。

startForeground(0, notification); // Doesn't work...

startForeground(1, notification); // Works!!!

我希望这会奏效!

【讨论】:

  • NOTIFICATION_ID 在我的情况下是 555
  • 好的,你可以关注这个小伙伴stackoverflow.com/questions/44658923/…
  • 这个问题的确切解决方案,请检查它@bhaskar
  • 我已经明确提到它第一次有效,但第二次无效。我还添加了更高版本的条件,并在我的清单文件中添加了权限
猜你喜欢
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2019-08-28
  • 2012-02-02
相关资源
最近更新 更多