为什么我从ContentValues获得的newUri为空?以编程方式设置铃声

时间:2018-12-19 19:30:08

标签: android ringtone

我正在尝试将歌曲设置为铃声。 I have found a lot of ways to do it but nothing works.其中一种方法如下:

 private void setSongAsRingtone(Song song){
        File ringFile = new File(song.getPath());

        Log.d(tag, "Ring name: " + ringFile.getName());
        Log.d(tag, "Ring absolute path: " + ringFile.getAbsolutePath());
        Log.d(tag, "Activity: " + getActivity().toString());

        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, ringFile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, song.getTitle());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
        values.put(MediaStore.MediaColumns.SIZE, 26454);
        values.put(MediaStore.Audio.Media.ARTIST, song.getArtist());
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        values.put(MediaStore.Audio.Media.IS_ALARM, true);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        Uri uri = MediaStore.Audio.Media.getContentUriForPath(ringFile.getAbsolutePath());
        Uri newUri = getActivity().getContentResolver().insert(uri, values);
        RingtoneManager.setActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_RINGTONE, newUri);
    }

Logcat说:

D/RingtoneDialogFragment: Ring name: Jamal - Peron [Official Music Video].m4a
D/RingtoneDialogFragment: Ring absolute path: /storage/emulated/0/storage/emulated/0/Download/Jamal - Peron [Official Music Video].m4a
D/RingtoneDialogFragment: Activity: com.linkplayer.linkplayer.main.MainActivity@7bc8453
I/RingtoneManager: Save cache type :1, URI : content://0@media/external/audio/media/10557
W/RingtoneManager: Failed to open directly; attempting failover: java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
W/RingtoneManager: Failed to cache ringtone: java.io.IOException: java.lang.SecurityException: Uri is not ringtone, alarm, or notification: content://0@media/external/audio/media/10557
I/RingtoneManager: ringtone title : Jamal - Peron [Official Music Video], DRM : 0

但是 newUri对象为空,并且我有一些错误。也许有人知道为什么?

预先感谢您的帮助。祝你晚上愉快。

1 个答案:

答案 0 :(得分:0)

在插入(创建newUri)之前,我必须调用此方法:

String filePathToDelete = MediaStore.MediaColumns.DATA + "=\"" + ringtoneFile.getAbsolutePath() + "\"";
getActivity().getContentResolver().delete(uri, filePathToDelete, null);