【问题标题】:I need to add notification sound dynamically from raw folder - Android我需要从原始文件夹动态添加通知声音 - Android
【发布时间】:2015-06-15 05:51:03
【问题描述】:

我的原始文件夹中有一个名为“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() 行中出现错误。 我确实浏览了几个链接,包括How to set notification with custom sound in android 有没有更好(和正确)的方法?

【问题讨论】:

  • 该函数下方显示红色下划线,提示如下:“NotificationCompat.Builder类型中的方法setSound(Uri)不适用于参数()”
  • 我会尝试this answer to your linked-to question 的解决方案,它会创建一个Uri 并跳过毫无意义的getIdentifier() 调用。
  • 因为这里写的“notificationsound”只是一个例子,字符串将作为声音名称传递,因此我不能附加“/notificationsound”
  • 然后附加"/"+yourStringVariable,其中yourStringVariable 是“字符串将作为声音名称传递”。你仍然不需要getIdentifier() 电话。
  • 你的意思是:builder.setSound("android.resource://" + con.getPackageName() + "/" +"notificationsound" );它行不通。语法错误

标签: android notifications android-resources resource-id


【解决方案1】:

这是相同的解决方案。 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-29
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 2014-04-04
    • 1970-01-01
    • 2014-03-04
    相关资源
    最近更新 更多