android11从uri中读取path的方法
时间: 2024-02-23 16:02:13 浏览: 141
在 Android 11 及以上版本中,由于限制了对外部存储的访问,从 URI 中读取文件路径的方法发生了变化,可以使用以下方法:
public String getFilePathFromUri(Context context, Uri uri) {
String filePath = "";
if (DocumentsContract.isDocumentUri(context, uri)) {
// 如果是Document类型的URI,则通过Document ID获取文件路径
String documentId = DocumentsContract.getDocumentId(uri);
if (uri.getAuthority().equals("com.android.externalstorage.documents")) {
String[] split = documentId.split(":");
String type = split[0];
if (type.equals("primary")) {
filePath = Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
filePath = "/storage/" + type + "/" + split[1];
}
} else if (uri.getAuthority().equals("com.android.providers.downloads.documents")) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(documentId));
filePath = getDataColumn(context, contentUri, null, null);
} else if (uri.getAuthority().equals("com.android.providers.media.documents")) {
String[] split = documentId.split(":");
String type = split[0];
Uri contentUri = null;
if (type.equals("image")) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if (type.equals("video")) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if (type.equals("audio")) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = new String[]{split[1]};
filePath = getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if (uri.getScheme().equals("file")) {
filePath = uri.getPath();
}
return filePath;
}
private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
String column = "_data";
String[] projection = {column};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
在上述代码中,使用了 DocumentsContract
类来处理不同类型的 URI,同时还使用了 Environment.getExternalStorageDirectory()
方法来获取外部存储器的路径。由于这种方法仅适用于 Android 11 及以上版本,因此需要在代码中进行版本判断。
相关推荐

















