android - 转换内容 ://URI to actual path in Android 4. 4

标签 android filepath android-contentresolver

我尝试了一个运行良好的解决方案(见下文),但在 Android 4.4 中,对 startActivityForResult() 的调用会显示一个名为“Open from”的 Activity ,其中包含“Recent”、“Images” ”、“下载”以及几个可供选择的应用程序。当我选择“图像”并尝试解析返回的内容 URI(使用下面的代码)时,对 cursor.getString() 的调用返回 null。如果我使用 Gallery 应用程序选择完全相同的文件,cursor.getString() 会返回一个文件路径。我只在 API 级别 16 和 19 中对此进行了测试。在 16 中一切正常。就 19 而言,我必须选择 Gallery 或其他应用程序,否则它不起作用。

private String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try { 
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);

        return path;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

最佳答案

这将从 MediaProvider、DownloadsProvider 和 ExternalStorageProvider 获取文件路径,同时回退到您提到的非官方 ContentProvider 方法。

   /**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
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);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

source aFileChooser

关于android - 转换内容 ://URI to actual path in Android 4. 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19985286/

相关文章:

android - 我的应用程序在 android chrome 中运行良好,但在使用默认网络浏览器的 webview 中运行不正常

Android: "Cannot Resolve symbol ' addValueEventListener'"在 Firebase 中

android - 如何使用回收器适配器通过 android 中的 fragment 从设备检索歌曲列表

android - 关于如何从 URI 获取 Exif 数据的最终答案

android - android apk发布与Web服务

android - 通过 phonegap 应用程序中的 config.xml 配置 android Intent

java - Android Java 根据生产/暂存加载不同的设置?

linux - 适用于 Windows 的 XDG Basedir 目录

python - 为什么 os.normpath 不折叠前导双斜杠?

Python 在 Linux 上查找标准输入文件路径