I need to add notification sound dynamically from raw folder - Android

2.2k Views Asked by At

I have a "notificationsound.mp3" named file in my raw folder, along with many other sound files. I need to dynamically add the sound files to my generated notifications . My approach included adding finding the resource id of the raw/soundfile ,and adding it . "con" is the context passed . My code goes as follows

    //blah blah blah lines of code
   String soundname="notificationsound"; // this name will be changed dynamically which is passed via constructor
  int res_sound_id = con.getResources().getIdentifier(soundname, "raw", con.getPackageName());
   builder.setSound("android.resource://" + con.getPackageName() + "/"+ res_sound_id );
  //blah blah lines of code

Of course , I am gettning error in the builder.setSound() line , because of res_sound_id. I did go through couple of links including How to set notification with custom sound in android Is there a better(& correct) of doing the same?

1

There are 1 best solutions below

0
On

Well here is the solution for the same. 1) get the resource id 2) make a Uri object 3) call the .setSound() method

   String s="soundname" // you can change it dynamically
   int res_sound_id = con.getResources().getIdentifier(soundname, "raw", con.getPackageName());
   Uri u= Uri.parse("android.resource://" + con.getPackageName() + "/" +res_sound_id );
   builder.setSound(u);