【问题标题】:Android custom notification soundAndroid自定义通知声音
【发布时间】:2017-06-08 08:40:46
【问题描述】:

我必须在我的应用程序中更改通知声音。声音是从服务器下载的,所以它存储在我的应用程序存储中。不幸的是,没有播放声音。

File folder = new File(context.getFilesDir() + File.separator + "sounds");
File sound = new File(folder, "my-sound.mp3");

Notification notification = new Builder(context)
            .setContentText("test")
            .setContentTitle(context.getText(R.string.app_name))
            .setSmallIcon(R.drawable.notification_icon)
            .setSound(Uri.parse(sound.toString()))
            .build();

我也试图以不同的方式获得这个Uri:

.setSound(Uri.parse(sound.toString()))

或者保存在MediaStore:

ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, sound.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.Media.ARTIST, "Some Artist");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(sound.getAbsolutePath());
Uri soundUri = context.getContentResolver().insert(uri, values);

声音 Uri 路径现在等于 content://media/external/audio/media/1265,但仍然无法正常工作。

如果我设置默认声音,那么它可以正常工作。 .setSound(RingtoneManager.getDefaultUri(TYPE_NOTIFICATION))

【问题讨论】:

  • 检查文件没有损坏。可能在下载过程中损坏了。
  • 文件没有损坏
  • context.getContentResolver().insert() 的结果总是 null

标签: android audio notifications


【解决方案1】:

对于存储在内部存储中的文件,您可以使用 FileProvider。

将提供程序添加到 AndroidManifest.xml

<provider
    android:authorities="my.file.provider"
    android:name="android.support.v4.content.FileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider> 

然后添加带有正文的新xml文件

<paths>
    <files-path name="sounds" path="sounds/"/>
</paths> 

在 setSound 之前你必须给 Android 系统授予 grandUriPermission

Uri soundUri = FileProvider.getUriForFile(context, "my.file.provider", sound);
context.grantUriPermission("com.android.systemui", soundUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

...

.setSound(soundUri)

【讨论】:

  • getUriForFile() 的最后一个参数代表什么?
  • 它是File 对象,用于您要授予访问权限的文件
【解决方案2】:

自定义声音使用这个

NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);
     mBuilder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));

默认通知声音使用这个

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);

【讨论】:

    猜你喜欢
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多