Search code examples
androidreact-nativeforeground-serviceforegroundnotification

Android 13: User can dismiss notification even after setting "setOnGoing(true)"


I am making a foreground service and as we know that such services need a notification to keep running. However since Android 13, the user can dismiss it just by swiping, thus the app is killed.

I tried to use setOnGoing(true) on the notification builder but no use.

I need to make the notification non-dismissable.

This is my code in Kotlin .

      private fun startForegroundServiceWithNotification() {
        Log.d("myTag", "startForegroundServiceWithNotification")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = CHANNEL_ID
            val channelName = "Wish2Go step counter"
            val chan = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            service.createNotificationChannel(chan)
        }


        var builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setOngoing(true)
            .setContentTitle("Counting steps")
            .setPriority(NotificationCompat.PRIORITY_HIGH)

        var notification = builder.build()
        notification.flags = Notification.FLAG_ONGOING_EVENT
        startForeground(1001, notification)

    }

Solution

  • I found the issue i had, apparently that i forgot to set the smallIcon for my notification

    private fun startForegroundServiceWithNotification() {
        Log.d("myTag", "startForegroundServiceWithNotification")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = CHANNEL_ID
            val channelName = "Wish2Go step counter"
            val chan = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            service.createNotificationChannel(chan)
        }
    
    
        var builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setOngoing(true)
            .setContentTitle("Counting steps")
            .setContentText("Open the app to see how are you doing.")
            .setSmallIcon(R.mipmap.ic_launcher_round) //Missing this was the issue 
            .setPriority(NotificationCompat.PRIORITY_HIGH)
    
        var notification = builder.build()
        notification.flags = Notification.FLAG_ONGOING_EVENT
        startForeground(1001, notification)
    
    }
    

    After setting the small Icon the notification acted as expected .