Reputation: 1834
I have to change notification sound in my app. The sound is downloaded from the server so it is stored in my app storage. Unfortunately, the sound is not played.
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();
I also tried to get this Uri
differently:
.setSound(Uri.parse(sound.toString()))
Or save it in 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);
Sound Uri path is now equal content://media/external/audio/media/1265
and still its not working.
If I set default sound then it is working correctly. .setSound(RingtoneManager.getDefaultUri(TYPE_NOTIFICATION))
Upvotes: 1
Views: 2587
Reputation: 56
For files stored in Internal Storage you can use FileProvider.
Add provider to 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>
then add new xml file with body
<paths>
<files-path name="sounds" path="sounds/"/>
</paths>
before setSound you have to grandUriPermission to Android System
Uri soundUri = FileProvider.getUriForFile(context, "my.file.provider", sound);
context.grantUriPermission("com.android.systemui", soundUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
...
.setSound(soundUri)
Upvotes: 4
Reputation: 3104
For Custom Sound Use this
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));
for Default Notification sound use this
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
Upvotes: 1