将内容:// URI转换为Android 4.4中的实际路径

Rag*_*are 62 android filepath android-contentresolver

我尝试了一个解决方案(见下文)工作正常,除了在Android 4.4中调用startActivityForResult()一个名为"Open from"的活动,其中包含"Recent","Images","Downloads"以及几个可供选择的应用程序.当我选择"图像"并尝试解析返回的内容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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Kis*_*ela 94

这将从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());
}
Run Code Online (Sandbox Code Playgroud)

来源 aFileChooser

  • 在Oreo的Downloads文件夹中抛出文件的异常 (11认同)
  • 这个utils并不完美,会在On Galaid S7,Andorid N API24上导致java.lang.RuntimeException.错误是列'_data'在相机拍照时不存在. (6认同)
  • @KishanVaghela此代码不适用于来自GoogleDrive和Uri的文件类型=>"content://com.google.android.apps.docs.storage/document/acc%3D3%3Bdoc%3D1259" (3认同)
  • 效果很好。要添加的一件事是,为了使我的上传代码(通过改造)正常工作,我必须在返回的String的开头附加“ file://”。 (2认同)

Com*_*are 45

将内容:// URI转换为Android 4.4中的实际路径

在任何Android版本上都没有可靠的方法.A content:// Uri不必表示文件系统上的文件,更不用说您可以访问的文件.

Android 4.4提供存储框架的更改只会增加您遇到content:// Uri值的频率.

如果你得到一个content:// Uri,请使用消耗它ContentResolver和方法,如openInputStream()openOutputStream().

  • @TomReznik:不要求“ACTION_GET_CONTENT”返回已由“MediaStore”索引的“Uri”。 (2认同)
  • @CommonsWare感谢您的回答,每个人似乎都在做海报所做的事情,尽管从来没有任何保证它总能奏效.我现在的问题是,如果我们需要一个File而不是一个InputStream,这是否意味着我们必须将InputStream转换为File? (2认同)
  • @a_secret:首先,我会尝试为你要解决的任何问题找到一些其他的解决方案,一个不涉及`文件'的问题(参见[我的这个咆哮](http://commonsware.com/blog/) 2013/08/07/for-android-apis-think-streams-not-files.html)去年关于这个主题).否则,是的,您需要将`InputStream`的内容流式传输到您自己的本地文件. (2认同)

Mak*_*ack 9

我也一直面临这个问题,但在我的情况下,我想要做的是指定一个具体的Uri到画廊,以便我以后可以使用裁剪.看起来在KitKat的新文档浏览器中我们不能再这样做,除非你在导航抽屉中选择galery,并且,就像你说的那样,直接从那里打开图像或文件.

在Uri的情况下,您仍然可以从文档浏览器打开时检索路径.

    Intent dataIntent= new Intent(Intent.ACTION_GET_CONTENT);
    dataIntent.setType("image/*"); //Or whatever type you need
Run Code Online (Sandbox Code Playgroud)

然后在onActivityResult中:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == ACTIVITY_SELECT_IMAGE && resultCode == RESULT_OK) {
        myUri = data.getData();
        String path = myUri.getPath();
        openPath(myUri);

    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要打开具有该路径的文件,您只需使用内容解析器:

public void openPath(Uri uri){
    InputStream is = null;
    try {
        is = getContentResolver().openInputStream(uri);
        //Convert your stream to data here
        is.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

它是在Google API中引入的.你可以试试这个:

private Bitmap getBitmapFromUri(Uri uri) throws IOException {
    ParcelFileDescriptor parcelFileDescriptor =
            getContentResolver().openFileDescriptor(uri, "r");
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
    parcelFileDescriptor.close();
    return image;
}
Run Code Online (Sandbox Code Playgroud)

  • 当我需要文件时怎么办? (2认同)