4

Android 13

Create a local notification with a custom sound

I have my event_sound.mp3 in my res/raw/event_sound.mp3

I have the following notification

val notification = NotificationCompat.Builder(context, channelId)
    .setContentTitle(title)
    .setContentText(description)
    .setSmallIcon(R.drawable.bell)
    .setAutoCancel(true)
    .setContentIntent(pendingIntent)
    .setSound(getUriSoundFile(context))
    .build()

I have the following method to extract the sound file which is in my data module.

 private fun getUriSoundFile(context: Context): Uri {
        val uri = Uri.parse("android.resource://" + "me.androidbox.data" + "/raw/" + "event_sound.mp3")

        return uri
    }

When I check the full path I get the following:

android.resource://me.androidbox.data/raw/event_sound.mp3

I have set my channels in my Application class like this:

  private fun createNotificationChannel(listOfChannel: Map<String, String>) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            listOfChannel.map { mapOfChannel ->
                val notificationManager = getNotificationManager()
                val notificationChannel = NotificationChannel(
                    mapOfChannel.key,
                    mapOfChannel.value,
                    NotificationManager.IMPORTANCE_HIGH
                )

                notificationManager.createNotificationChannel(notificationChannel)
            }
        }
    }

However, the notification only sounds the default and never plays my custom sound.

UPDATE ====

I have the following in my Application class. The event_sound is in the following directly

raw/event_sound.mp3

And this is the debug output android.resource://me.androidbox.presentation/2131558400

This is my updated code:

private fun createNotificationChannel(listOfChannel: Map<String, String>) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        listOfChannel.map { mapOfChannel ->
            val notificationManager = getNotificationManager()
            val notificationChannel = NotificationChannel(
                mapOfChannel.key,
                mapOfChannel.value,
                NotificationManager.IMPORTANCE_HIGH
            )

            val audioAttributes = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
                .build()

            notificationChannel.setSound(getUriSoundFile(), audioAttributes)
            notificationManager.createNotificationChannel(notificationChannel)
        }
    }
}
ant2009
  • 27,094
  • 154
  • 411
  • 609

2 Answers2

6

Problem Description : After Android 13 all notification sounds regardless of in app selection is set to default sound

Make sure your notification sound is in mp3 format in res/raw.

You can leave the else part as is.

New Answer


private fun getUriSoundFile(context: Context): Uri {
        val uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/" + R.raw.event_sound.mp3)

        return uri
    }


private fun createNotificationChannel(listOfChannel: Map<String, String>) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        listOfChannel.map { mapOfChannel ->
            val notificationManager = getNotificationManager()
            val notificationChannel = NotificationChannel(
                mapOfChannel.key,
                mapOfChannel.value,
                NotificationManager.IMPORTANCE_HIGH
            )

            val audioAttributes = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build()

            notificationChannel.setSound(getUriSoundFile(), audioAttributes)
            notificationManager.createNotificationChannel(notificationChannel)
        }
    }
}

Old Answer

private fun createNotificationChannel() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val audioAttributes = AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
                    .build()
    
                val uri = Uri.parse("android.resource://$packageName/${R.raw.sample_sound}")
    
                val channel = NotificationChannel(
                    CHANNEL_ID,
                    "Channel Name",
                    NotificationManager.IMPORTANCE_DEFAULT
                ).apply {
                    description = "Description"
                    setSound(uri, audioAttributes)
                }
                val notificationManager =
                    getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                notificationManager.createNotificationChannel(channel)
            }
        }
Arda Kazancı
  • 8,341
  • 4
  • 28
  • 50
  • I tried the code that you suggested. Howevever, the sound still displayed the default sound and not my custom one. I have updated my question with my latest code. – ant2009 Jul 11 '23 at 16:19
  • I updated my answer. Can you try again ? – Arda Kazancı Jul 11 '23 at 16:43
  • please share listOfChannel param value – Arda Kazancı Jul 12 '23 at 07:55
  • Thanks, The above code is working correctly for Android 11 device. However, I have an Adnroid 13 device and the above code doesn't work. I am just wondering from your problem description, does that mean for Android 13 we cannot change the notification sound? – ant2009 Jul 12 '23 at 14:47
  • 1
    Technically we adjust their sound using all channels. In Android 13, I think it may be necessary to manage it manually. I think they will fix this in the future. – Arda Kazancı Jul 12 '23 at 15:40
1

here is a solved question for the same issue moreover I am attaching the referal link Android notification setSound is not working

String CHANNEL_ID="1234";

    Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.mysound);
    NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); 
    
  //For API 26+ you need to put some additional code like below:
    NotificationChannel mChannel;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mChannel = new NotificationChannel(CHANNEL_ID, Utils.CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                mChannel.setLightColor(Color.GRAY);
                mChannel.enableLights(true);
                mChannel.setDescription(Utils.CHANNEL_SIREN_DESCRIPTION);
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                        .build();
                mChannel.setSound(soundUri, audioAttributes);
    
                if (mNotificationManager != null) {
                    mNotificationManager.createNotificationChannel( mChannel );
                }
        }

   //General code:
     NotificationCompat.Builder status = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);     
                          status.setAutoCancel(true)
                                .setWhen(System.currentTimeMillis())
                                .setSmallIcon(R.drawable.logo)
                                //.setOnlyAlertOnce(true)
                                .setContentTitle(getString(R.string.app_name))
                                .setContentText(messageBody)
                                .setVibrate(new long[]{0, 500, 1000})
                                .setDefaults(Notification.DEFAULT_LIGHTS )
                                .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" +mContext.getPackageName()+"/"+R.raw.apple_ring))
                                .setContentIntent(pendingIntent)
                                .setContent(views);
                        
                        mNotificationManager.notify(major_id, status.build());
Sweety SK
  • 351
  • 1
  • 10