Skip to content Skip to sidebar Skip to footer

How To Add Sound To Notification?

How do you add sound to a notification created by NotificationCompat.Builder? I created a raw folder in res and added the sound there. So how do I now add it to notification? This

Solution 1:

I'm guessing the problem here is how to reference the sound with a Uri, as there is an obvious method in the NotificationCompat.Builder class - setSound(Uri soundUri).

To access your raw resources you need to create the Uri as follows:

android.resource://[PACKAGE_NAME]/[RESOURCE_ID]

So the code could end up looking like that:

Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
mBuilder.setSound(sound);

Solution 2:

To play a sound with your notification:

Notification notification = new Notification(icon, tickerText, when);

Do normal notification procedures

To play the default sound with your notification:

notification.defaults |= Notification.DEFAULT_SOUND;

To play a custom sound with your notification:

notification.sound = Uri.parse("file:///sdcard/notification/notification.mp3");

Then just use the notification manager to send the notification. If both of these statements are used, the application will default to using the default sound.


Solution 3:

For Android 8 (Oreo) and above you should use Notification Channel to show notifications, and they will automatically have sound if you haven't disabled it.

For older devices you can set sound with Notification Builder. You can use Notification.Builder.setSound() to set custom sound, or you can use

Notification.Builder.setDefaults(NotificationCompat.DEFAULT_SOUND) to set default sound.

There are also defaults for vibration and lights


Post a Comment for "How To Add Sound To Notification?"