2

我的原始文件夹中有一个名为“notificationsound.mp3”的文件,以及许多其他声音文件。我需要将声音文件动态添加到我生成的通知中。我的方法包括添加查找原始/声音文件的资源 ID,然后添加它。“con”是传递的上下文。我的代码如下

    //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

当然,由于 res_sound_id,我在 builder.setSound() 行中遇到错误。我确实通过了几个链接,包括如何在android中使用自定义声音设置通知 是否有更好的(和正确的)做同样的事情?

4

1 回答 1

2

那么这里是相同的解决方案。1) 获取资源 id 2) 创建一个 Uri 对象 3) 调用 .setSound() 方法

   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);
于 2015-06-14T21:51:03.957 回答