4

Android 11
targetApi 30
不请求READ_EXTERNAL_STORAGEWRITE_EXTERNAL_STORAGE
使用SAF api 来获取这样的 uri:
“content://com.android.providers.media.documents/document/document%3”
并像这样解析 uri:

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;
}

我在低于 android 11 的手机上得到正常值,但在 android 11 手机上得到空值

好吧,我想获取文件的真实路径或名称

谁能帮帮我?<br />谢谢!

4

0 回答 0