How to set audio as ringtone programmatically above Android N

流过昼夜 提交于 2020-01-13 03:48:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!