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

我尝试了一种运行良好的解决方案(请参见下文),但在Android 4.4中,该调用调出startActivityForResult()了一个名为“打开自”的活动,该活动包含“最近”,“图像”,“下载”以及可供选择的多个应用。当我选择“图像”并尝试解析返回的内容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();

        }

    }

}


一只萌萌小番薯
浏览 469回答 3
3回答

翻翻过去那场雪

将content:// URI转换为Android 4.4中的实际路径在任何Android版本上都没有可靠的方法来执行此操作。A content:// Uri不必代表文件系统上的文件,更不用说您可以访问的文件了。Android 4.4提供存储框架的更改只是增加了您遇到content:// Uri值的频率。如果得到a content:// Uri,请使用ContentResolver和方法(例如openInputStream()和)使用它openOutputStream()。

森林海

我也一直面临这个问题,但就我而言,我想做的就是为Gallery指定一个具体的Uri,以便以后可以使用裁剪。看起来在新的KitKat文档浏览器中,除非您在导航抽屉中选择galery,然后像您说的那样直接从那里打开图像或文件,否则我们将无法再这样做。在Uri情况下,从文档浏览器打开时,您仍然可以检索路径。    Intent dataIntent= new Intent(Intent.ACTION_GET_CONTENT);    dataIntent.setType("image/*"); //Or whatever type you need然后在onActivityResult中:@Overridepublic 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);    }}如果您需要然后使用该路径打开文件,则只需使用Content Resolver: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();    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS