android – 使用ACTION_GET_CONTENT选择文件路径的正确方法

我在我的应用程序中实现了一个文件选择器,如下所示:

Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Title"), FILE_PICK);

这是一个众所周知的问题,你无法通过这种方式轻松获取实际的文件位置,因为Intent将返回一些你无法真正用来创建File对象的奇怪的Uri.

我正在使用此方法来获取实际的文件路径:

/**
 * 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 the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

这适用于某些文件,有些则不适用.现在我注意到当我从“Downloads”文件夹中选择一个文件时它不起作用.它会跳过上面的所有if语句并返回null.

什么是正确的方法,获得实际选择的文件路径会更可靠?

解决方法:

I have a file picker implemented in my app like this

那不是“文件选择器”.这是一个内容选择器.

I need a way to be able to pick any file on Android device so that I can upload it to my backend.

嗯,这很大程度上取决于你在这句话中的字面意义.

ACTION_GET_CONTENT一般不是问题.但是,你得到的不一定是文件.但是,您仍然可以上传它们,假设您用于上传的任何内容都允许您从InputStream上传.如果是这样,请在ContentResolver上使用openInputStream(),传入Uri,以获取要使用的InputStream.

如果您真的需要它作为实际文件,您可以直接在您的应用程序中实现文件选择器UI. There are libraries for this.但是,您将无法访问所有文件 – 特别是,您无法使用此文件从Android 4.4上的removable storage上传文件.

相关文章

Android 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...