4

I want to create a notification without any sounds. How can I do this? I tried the code below but it's not working for me:

notification = mBuilder
        .setStyle(notiStyle)
        .setSmallIcon(notificationIcon)
        .setTicker(title)
        .setWhen(0)
        .setAutoCancel(true)
        .setContentTitle(title)
        .setContentIntent(resultPendingIntent)
        .setSound(null).build();
Matt
  • 5,404
  • 3
  • 27
  • 39
Mehmet Demir
  • 238
  • 2
  • 8
  • duplicate of http://stackoverflow.com/questions/7655164/android-notification-sound-disable – Gueorgui Obregon Mar 09 '16 at 19:59
  • There's a bug in the Notification Channels when targeting API 26 (Android O) https://stackoverflow.com/questions/45919392/disable-sound-from-notificationchannel – Daniel F Aug 28 '17 at 14:26

3 Answers3

5

You can create the NotificationCompat.Builder object without using setSound(). This will create a notification without any sound.

notification = mBuilder
                .setStyle(notiStyle)
                .setSmallIcon(notificationIcon)
                .setTicker(title)
                .setWhen(0)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentIntent(resultPendingIntent)
                .build();
Shadab Ansari
  • 7,022
  • 2
  • 27
  • 45
4

After your notification builder, add

notification.defaults = 0;

to tell the notification manager not to make any default values when not specified (eg. you set to null so it takes the default value, adding this will remove this behavior and so disable sounds completely).

Chaoz
  • 2,119
  • 1
  • 20
  • 39
  • 1
    in android o its removed – Saef Myth Feb 13 '18 at 05:27
  • 3
    @Sakiboy the sound comes from the channel when you set the importance of the notification channel to low it should not play sound ,but when you create channel in the first time you cant created it again it stays in the device you need to remove change through apis or create anew channel name – Saef Myth Feb 14 '18 at 16:50
  • 2
    Right. So it’d be a good idea to handle these things with care when creating them (turn off all the sounds and vibrations?) Also `setAlertOnlyOnce()` works for notifications that update, this could be helpful in certain places. Since you can’t update you’re actual notification object. – Sakiboy Feb 14 '18 at 17:33
1

In Android 26+ (Oreo) you do this by setting notification channel importance level to 'IMPORTANCE_LOW' or below.

val importance = NotificationManager.IMPORTANCE_LOW
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
    description = descriptionText
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
egis112
  • 23
  • 5