I'm using a foreground service on Android.
This service should never be terminated while the user is on the corresponding screen, so I've ensured it won't be terminated by calling startForeground().
Additionally, I've set setOngoing(true) to prevent the Notification from being dismissed.
val notification = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.app_icon)
.setContent(contentViews)
.setContentIntent(getMyPendingIntent(REQUEST_CODE))
.setCategory(Notification.CATEGORY_SERVICE)
.setOngoing(true)
.build()
service.startForeground(notificationId, notification)
I've tested on devices running Android 12, 13, and 14.
On Android 12, the Notification remains visible and does not disappear even when swiped by the user.
However, on devices running Android 13 and 14, the Notification disappears.
I've also seen similar information in the official documentation, stating that setting setOngoing(true) should prevent dismissal.
What could be the cause of this issue, and how should I address it?
I checked the similar issue: Android 13: User can dismiss notification even after setting "setOnGoing(true)"
In my app, I'm using a custom view. However, even when I removed the custom view and replaced it with contentTitle and contentText similar to a link, the Notification still gets dismissed."
val notification = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.app_icon)
// .setContent(contentViews)
.setContentTitle("Hello")
.setContentText("World")
.setContentIntent(getMyPendingIntent(REQUEST_CODE))
.setCategory(Notification.CATEGORY_SERVICE)
.setOngoing(true)
.build()
service.startForeground(notificationId, notification)
Just for reference, this service is bound from a Fragment as a bind service.
val intent = Intent(requireContext(), service)
requireContext().bindService(intent, object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val notification = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.app_icon)
.setContent(contentViews)
.setContentIntent(getMyPendingIntent(REQUEST_CODE))
.setCategory(Notification.CATEGORY_SERVICE)
.setOngoing(true)
.build()
(service as? MyService)?.startForeground(notificationId, notification)
}
override fun onServiceDisconnected(name: ComponentName) { }
}, Service.BIND_AUTO_CREATE)