23

I want to set a custom notification sound from a raw mp3 or wav file in my app. Below is my code

private void sendMyNotification(String message) {
    Intent intent;
    if (sharedPreferences.getBoolean(SPConstants.IS_LOGGED_IN, false)) {
        intent = new Intent(this, ActivityNotification.class);
    } else {
        intent = new Intent(this, ActivitySplash.class);
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.panic);
    AudioManager manager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    manager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
        notificationManager.createNotificationChannel(mChannel);
    }
    notificationManager.notify(0, notificationBuilder.build());
}

The panic audio file resides in res->raw. I have tried to use both mp3 and wav formats of the sound but nothing seems to work to set the notification sound. I am currently testing on Pixel 2 OS 8.1.

Any suggestions what could be the issue?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
WISHY
  • 11,067
  • 25
  • 105
  • 197
  • 2
    Hmmm. I was facing the similar issue. The only solutions that I have found were to give a possibility to set it by OS notification channel settings. It is because of once you create a notification channel you cannot change its settings programmatically (but maybe I have done it wrong). If you will find any other solution I would love to know how to fix this. – Patryk Jabłoński Jun 25 '18 at 18:25
  • @PatrykJabłoński below answer by Khaled does seems to work only if you have not setContentIntent. – WISHY Jun 26 '18 at 02:51
  • I will definitely check it, but in my case, I use `setContentIntent`. Thanks for notifying me :) – Patryk Jabłoński Jun 26 '18 at 06:28
  • 1
    @PatrykJabłoński Yes that's the same issue with me as well. I am also using setContentIntent but does not work in that case. – WISHY Jun 26 '18 at 07:11
  • hmmm, I am just wondering if this is not an OS bug. `setContentIntent` has nothing to do with notification sound/vibration settings in my opinion. I will take a look at that because this might be a thing that should be reported to the Google – Patryk Jabłoński Jun 26 '18 at 07:23
  • @PatrykJabłoński keep me posted for the same – WISHY Jun 26 '18 at 09:02
  • make sure to UNINSTALL the APP. – Ehsan Ghasaei May 12 '21 at 23:09

3 Answers3

50
  • Tested blow code and worked with me as expected.

  • Add Content intent and that still working without any issues with me.

    private void sendMyNotification(String message) {
    
    Intent intent = new Intent(this, SplashActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    
    Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.correct_answer);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentIntent(pendingIntent);
    
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    
        if(soundUri != null){
            // Changing Default mode of notification
            notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
            // Creating an Audio Attribute
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();
    
            // Creating Channel
            NotificationChannel notificationChannel = new NotificationChannel("CH_ID","Testing_Audio",NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setSound(soundUri,audioAttributes);
            mNotificationManager.createNotificationChannel(notificationChannel);
        }
    }
    mNotificationManager.notify(0, notificationBuilder.build());
    }
    

Update

  • You may need uninstall the app to alter sound settings, Check out these link for more details.
Khaled Lela
  • 7,831
  • 6
  • 45
  • 73
  • 1
    if you set content intent to notification builder then this code does not work – WISHY Jun 26 '18 at 02:50
  • @WISHY Updated my answer with `setContentIntent(pendingIntent)` and still working with me, You may need uninstall the app to alter sound settings, Check out these [link](https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels) for more details. – Khaled Lela Jun 27 '18 at 07:36
  • @KhaledLela I am getting this problem : https://stackoverflow.com/q/53913251/1318946 – Pratik Butani Dec 24 '18 at 12:12
  • @KhaledLela How to do this for android 10 – Maveňツ Mar 31 '20 at 08:38
  • 4
    The uninstall part seems to be crucial - without that it didn't work for me on a couple of phones – dorsz May 14 '20 at 06:36
  • 4
    Uninstalling and reinstalling app helped me a lot, thanks – Unaisul Hadi Jun 28 '20 at 05:12
  • 1
    i was doing what you told above but was not working until reinstalled the app, thanks for your help. – Usama Saeed US Dec 04 '20 at 10:35
  • I'm getting the same problem works with uninstall but I have 3 different notification sound and I want to change programmatically, how can I do that without telling use to uninstall the app ? – Web.11 Jun 01 '22 at 13:46
4

Simple answer:

Uri soundUri = Uri.parse(
                         "android.resource://" + 
                         getApplicationContext().getPackageName() +
                         "/" + 
                         R.raw.push_sound_file);

AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_ALARM)
            .build();

// Creating Channel
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
                                                      "YOUR_CHANNEL_NAME",
                                                      NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                           .createNotificationChannel(notificationChannel);
oxied
  • 1,773
  • 19
  • 14
1

Late but might be helpful to some one, just add below line in your NotificationCompat.Builder() instance:

.setSound("your sound uri",AudioManager.STREAM_NOTIFICATION)

Note: As NotificationCompat.Builder() is backward compatible , so AudioAttributes etc in notification channel is not required

mecky roon
  • 11
  • 2