Principle: By distinguishing different Uri, extracting the ID,
Requires android.permission.MANAGE_EXTERNAL_STORAGE permission
Uri processing method of android.externalstorage type content:
Just get the path after "primary:" directly, followed by the relative path.
Uri processing method of media type content:
Similar to the next one, enter the data table to look up after getting the ID.
Uri processing method of android.providers type content:
Enter the MediaStore.Files table to query the _data field. The old version of _data obtained by directly querying the uri is no longer valid.
The code posted below is suitable for all types of files. If you only need to query files of a certain media, you only need to change the query table.
MediaStore.Files.getContentUri("external")
MediaStore.Files.getContentUri("internal")
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
MediaStore.Video.Media.INTERNAL_CONTENT_URI
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
MediaStore.Images.Media.INTERNAL_CONTENT_URI
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
MediaStore.Audio.Media.INTERNAL_CONTENT_URI
MediaStore.Downloads.Media.EXTERNAL_CONTENT_URI
MediaStore.Downloads.Media.INTERNAL_CONTENT_URI
the code
public static String Uri2Path(Context context, Uri uri) {
if (uri == null) {
return null;
}
if(ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
return uri.getPath();
}
else if(ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
String authority = uri.getAuthority();
if(authority.startsWith("com.android.externalstorage")) {
return Environment.getExternalStorageDirectory() + "/" + uri.getPath().split(":")[1];
}
else {
String idStr = "";
if(authority.equals("media")) {
idStr = uri.toString().substring(uri.toString().lastIndexOf('/') + 1);
}
else if(authority.startsWith("com.android.providers")) {
idStr = DocumentsContract.getDocumentId(uri).split(":")[1];
}
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(MediaStore.Files.getContentUri("external"),
new String[] {
MediaStore.Files.FileColumns.DATA},
"_id=?",
new String[]{
idStr}, null);
if (cursor != null) {
cursor.moveToFirst();
try {
int idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
return cursor.getString(idx);
} catch (Exception e) {
} finally {
cursor.close();
}
}
}
}
return null;
}