Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);
mBuilder.setSound(sound);
I had copied the mp3 (notification_mp3.mp3) file into the raw folder in the res folder. When the notification is triggered it produces given mp3 sound upto Android Nougat but default sound in Android Oreo. I had referred many sites but nothing worked on Android Oreo. I didn't find any changes in Android Docs regarding notification sound in Android O & above. What changes should be done to make this code working in Android O too?
To set a sound to notifications in Oreo, you must set sound on NotificationChannel
and not on Notification Builder
itself. You can do this as follows
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.notification_mp3);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel("YOUR_CHANNEL_ID",
"YOUR CHANNEL NAME",
NotificationManager.IMPORTANCE_DEFAULT)
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
context.getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription(msg);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setSound(sound, attributes); // This is IMPORTANT
if (mNotificationManager != null)
mNotificationManager.createNotificationChannel(mChannel);
}
This will set a custom sound to your notifications. But if the app is being updated and the notification channel is used before, it won't be updated. i.e. you need to create a different channel and set sound to it to make it work. But this will show multiple channels in the notifications section of app info of your app. If you are setting sound to an entirely new channel that is fine, but if you want the channel being used before, you have to delete the existing channel and recreate the channel. To do that you can do something like that before creating channel
if (mNotificationManager != null) {
List<NotificationChannel> channelList = mNotificationManager.getNotificationChannels();
for (int i = 0; channelList != null && i < channelList.size(); i++) {
mNotificationManager.deleteNotificationChannel(channelList.get(i).getId());
}
}