调取相册 SD Uri 转换路径

@SuppressLint("NewApi")
private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
    String filePath = null;
    if (DocumentsContract.isDocumentUri(context, uri)) {
        // 如果是document类型的 uri, 则通过document id来进行处理
        String documentId = DocumentsContract.getDocumentId(uri);
        if (isMediaDocument(uri)) { // MediaProvider
            // 使用':'分割
            String id = documentId.split(":")[1];
            String selection = MediaStore.Images.Media._ID + "=?";
            String[] selectionArgs = {id};
            filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
        } else if (isDownloadsDocument(uri)) { // DownloadsProvider
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
            filePath = getDataColumn(context, contentUri, null, null);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // 如果是 content 类型的 Uri
        filePath = getDataColumn(context, uri, null, null);
    } else if ("file".equals(uri.getScheme())) {
        // 如果是 file 类型的 Uri,直接获取图片对应的路径
        filePath = uri.getPath();
    }
    return filePath;
}
/**
 * 获取数据库表中的 _data 列,即返回Uri对应的文件路径
 *
 * @return
 */
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    String path = null;

    String[] projection = new String[]{MediaStore.Images.Media.DATA};
    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
            path = cursor.getString(columnIndex);
        }
    } catch (Exception e) {
        if (cursor != null) {
            cursor.close();
        }
    }
    return path;
}
/**
 * @param uri the Uri to check
 * @return Whether the Uri authority is MediaProvider
 */
private static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri the Uri to check
 * @return Whether the Uri authority is DownloadsProvider
 */
private static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值