正在进行的通知未取消

Ongoing Notification not canceling

我们正在使用 jobScheduler 来 运行 一个周期性的天气网络调用,其结果被发布到一个持续的天气通知中。

以下是我们如何在 jobService 中创建通知:

private fun createNotification(selectedLocation: City) {
        val resultIntent = Intent(context, SplashActivity::class.java)
            resultIntent.putExtra(AppConstants.IS_ONGOING, true)
            resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)

            val resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0)
            val notificationView = getComplexNotificationView(selectedLocation) ?: return

            val notification = NotificationCompat.Builder(context, context.packageName)
                    .setPriority(NotificationCompat.PRIORITY_LOW)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setSmallIcon(getSmallIconResource(context,
                            if (settings.isFahrenheitEnabled())
                                selectedLocation.currentObservation!!.tempF!!
                            else
                                selectedLocation.currentObservation!!.tempC!!))
                    .setVibrate(null)
                    .setWhen(System.currentTimeMillis())
                    .setCustomContentView(notificationView)
                    .setContentIntent(resultPendingIntent)
                    .setOngoing(true)
                    .setAutoCancel(false)
                    .setGroup(AppConstants.NOTIFICATION_GROUP_ONGOING)
                    .build()

            NotificationManagerCompat.from(context).notify(ONGOING_NOTIFY_ID, notification)
    }

在我们应用程序的设置中,用户可以禁用持续通知。以下是我们尝试取消它的方式:

val jobScheduler: JobScheduler? = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler?.cancel(OngoingNotificationJobService.ONGOING_JOB_ID)

NotificationManagerCompat.from(context).cancel(OngoingNotificationJobService.ONGOING_JOB_ID)

问题:

取消调用不会清除通知。我做错了什么?

您必须 "NotificationManagerCompat.from(context).cancel()" 您之前的 ONGOING_NOTIFY_ID 而不是您的 ONGOING_JOB_ID ;)