在安卓系统中,独立于位置打开Uri文件

3
我需要一些帮助来理解如何在安卓系统中打开文件。我的具体问题与打开图像文件有关。在我的应用程序中,用户使用自己选择的相机应用程序拍下照片,然后我对返回的图像进行操作。根据手机型号、Android版本和所选的相机应用程序,onActivityResult中返回的参数不同。有时我会得到一个URI,有时只是一张图片,有时两者都有。
启动相机的代码如下:
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_IMAGE); 

我接着收到的结果如下:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_IMAGE && resultCode == Activity.RESULT_OK) {
        Log.d(TAG,"In onActivityResult");
        Bitmap imageBmp = null;
        Uri imageUri = data.getData();

        if (data.getExtras() != null) {
        imageBmp = (Bitmap)data.getExtras().get("data");
        Log.d(TAG,"Got Bitmap");
        }
        ...
    }
}

当我收到一个URI而不是一张图片时,我的问题就出现了。如果imageBmp为空,则需要从URI加载图片。我已经在几个设备/应用程序组合中测试过这一点。有时候文件存在于内部存储器上,有时候则在SD卡上。如果文件存在于SD卡上,我会使用managedQuery来获取文件。

String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(imageUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);                        
cursor.moveToFirst();
imageFileName = cursor.getString(column_index);  
File imageFile = new File(imageFileName);
...

如果文件在内部存储中,那么我会得到一个FileNotFoundException。

我的具体问题是:如何修改代码以打开独立于文件系统上的文件,只知道URI?我想要做的事情类似于:

File imageFile = new File(imageUri);

但是File不接受Uri对象。 我使用托管查询将其转换为字符串。

我更普遍的问题是为什么我需要首先执行查询? 为什么不能只使用返回的URI?

1个回答

8

您需要使用contentResolver来访问作为uri传递的内部文件

ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(imageUri);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接