问题
In the past, we could use code below to set an audio file as 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 will receive a SecurityException
for getContentResolver().insert()
that we don't have permission of MANAGE_DOCUMENTS
, which will always be thrown even if we declare this permission in AndroidManifest
.
I really want to set audio file as ringtone since I want users of my app to have the ability of customizing notification sound. In fact we can use builder.setSound(Uri.fromFile(musicFile))
before N for Notification
, but this approach is also forbidden on N and will throw a FileUriExposedException
.
来源:https://stackoverflow.com/questions/39285228/how-to-set-audio-as-ringtone-programmatically-above-android-n