以下方法对于大部分uri都能获取到path,目前发现的content://com.android.providers.downloads.documents/document/410
无法获取
public static String getPathFromUri(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 id = DocumentsContract.getDocumentId(uri);String[] split = id.split(":");if (id.startsWith("raw:")) {return id.replaceFirst("raw:", "");}String idStr = id;if (authority.startsWith("com.android.providers")) {if (split.length > 1) {idStr = 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;}
以下方法,传入uri通过ContentResolver获取的方法对于大部分的路径根本获取不到,不要被误导
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {Cursor cursor = null;final String column = "_data";final String[] projection = {column};try {cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);if (cursor != null && cursor.moveToFirst()) {final int column_index = cursor.getColumnIndexOrThrow(column);return cursor.getString(column_index);}} catch (Exception e) {} finally {if (cursor != null)cursor.close();}return null;}