How to get real file path or file name from document uri on Android 11 And targetApi 30

1k views Asked by At

Android 11
targetApi 30
do not request READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE
use SAF api to get a uri like this:
"content://com.android.providers.media.documents/document/document%3"
and parse the uri like this:

public static String getRealPath(uri) {
    String docId = DocumentsContract.getDocumentId(uri);
    String[] split = docId.split(":");
    String type = split[0];
    Uri contentUri;
    switch (type) {
        case "image":
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            break;
        case "video":
            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            break;
        case "audio":
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            break;
        default:
            contentUri = MediaStore.Files.getContentUri("external");
    }
    String selection = "_id=?";
    String[] selectionArgs = new String[]{
            split[1]
    };

    return getDataColumn(getContext(), contentUri, selection, selectionArgs);
}

public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    String column = "_data";
    String[] projection = {
            column
    };
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(column);
            String value = cursor.getString(column_index);
            if (value.startsWith("content://") || !value.startsWith("/") && !value.startsWith("file://")) {
                return null;
            }
            return value;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return null;
}

and I get normal value on mobile phones below android 11, but empty value on android 11 mobile phones

Well, I want to get the file's real path or name

Can someone help me?
Thanks!

0

There are 0 answers