Android自定义通知声音

Android自定义通知声音,android,audio,notifications,Android,Audio,Notifications,我必须在我的应用程序中更改通知声音。声音是从服务器下载的,因此它存储在我的应用程序存储中。不幸的是,没有播放声音 File folder = new File(context.getFilesDir() + File.separator + "sounds"); File sound = new File(folder, "my-sound.mp3"); Notification notification = new Builder(context) .setConte

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

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

对于自定义声音,请使用此

对于默认通知声音,请使用以下命令


对于存储在内部存储器中的文件,可以使用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> 

检查文件是否已损坏。可能是在下载过程中,其已损坏。文件未损坏。根据上下文,我始终获取null。getContentResolver().insert()getUriForFile()的最后一个参数代表什么?它是您要授予访问权限的文件的
文件
对象
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
<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> 
<paths>
    <files-path name="sounds" path="sounds/"/>
</paths> 
Uri soundUri = FileProvider.getUriForFile(context, "my.file.provider", sound);
context.grantUriPermission("com.android.systemui", soundUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

...

.setSound(soundUri)