android - 我需要从原始文件夹动态添加通知声音 - Android

标签 android notifications android-resources resource-id

我的原始文件夹中有一个名为“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 是否有更好(且正确)的做法?

最佳答案

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

关于android - 我需要从原始文件夹动态添加通知声音 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30834710/

相关文章:

android - GridView 中的特定 TextView 未在应用程序初始化时更新

Android Studio - 全局设置构建目录(每台机器)

cordova - 每天使用 phonegap cordova 安排本地通知

android - 在 Android 中将 resourceId 分配给 Layout

java - Android - 饼图

android - 当应用程序从 Android 中的任务管理器中终止时如何获取事件?

ios - 包含 iOS 应用程序数据更改时更新 WatchKit 应用程序

android - 如何在android中创建自定义通知

android - 用不同颜色绘制 FILL_AND_STROKE 表格

android - Resources$NotFoundException 用于 Vivo 设备上的少数 Drawable