2015-06-14 25 views
2

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

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

当然,我gettning错误的builder.setSound()线,因为res_sound_id的。 我确实经历了几条链接,包括How to set notification with custom sound in android 有没有更好的(&正确)做同样的事情?

+0

示出了该函数如下红色下划线,提示示出如下: “的方法setSound(URI)在类型NotificationCompat.Builder不适用于参数()“ –

+0

我想尝试从[这个答案到你的链接到的问题](http://stackoverflow.com/a/13784557/115145)的解决方案,它创建一个'Uri'并跳过无意义的'getIdentifier()'调用。 – CommonsWare

+0

,因为这里写的“notificationsound”只是一个例子,字符串将作为声音名称传递,因此我不能附加“/ notificationsound” –

回答

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