How to set sound as ringtone programmatically above Android N

In the past, we could use the code below to set the sound file as a ringtone:

ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, musicFile.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "my music");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, 215454);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); // true for notification sound
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);

Uri uri = MediaStore.Audio.Media.getContentUriForPath(musicFile.getAbsolutePath());
Strint where = MediaStore.MediaColumns.DATA + "=\""
                + newSoundFile.getAbsolutePath() + "\"";
getContentResolver().delete(uri, where, null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(
        RingtonesPlaying.this, RingtoneManager.TYPE_RINGTONE, newUri);

However, if we run the code above Nougat (7.0, API 24), we get SecurityExceptionfor getContentResolver().insert()that we don’t have a permission MANAGE_DOCUMENTSthat will always be selected, even if we declare this permission in AndroidManifest.

I really want to set the sound file as a ringtone, since I want users of my application to be able to customize the notification sound. In fact, we can use builder.setSound(Uri.fromFile(musicFile))up to N for Notification, but this approach is also forbidden on N and will throw a FileUriExposedException.

+4

Source: https://habr.com/ru/post/1653395/


All Articles