简体   繁体   中英

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

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM