How to get the Uri from MediaStore via file path?

后端 未结 4 969
别那么骄傲
别那么骄傲 2020-12-15 12:53

In my program, I want to save a selected ringtone by it\'s file path, and then set it as the current ringtone later.

I have got the ringtone uri from RingtonePrefere

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 13:13

    Following code will return absolute path for content Uri of audio, video and image.

    public static String getRealPathFromURI(Context context, Uri contentUri) {
            Cursor cursor = context.getContentResolver().query(contentUri, null, null, null, null);
    
            int idx;
            if(contentUri.getPath().startsWith("/external/image") || contentUri.getPath().startsWith("/internal/image")) {
                idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            }
            else if(contentUri.getPath().startsWith("/external/video") || contentUri.getPath().startsWith("/internal/video")) {
                idx = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DATA);
            }
            else if(contentUri.getPath().startsWith("/external/audio") || contentUri.getPath().startsWith("/internal/audio")) {
                idx = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
            }
            else{
                return contentUri.getPath();
            }
            if(cursor != null && cursor.moveToFirst()) {
                return cursor.getString(idx);
            }
            return null;
        }
    

提交回复
热议问题