从Uri打开文件,独立于android中的位置

Joh*_*lay 3 android file

我可以使用一些帮助来理解如何在android中打开文件.我的具体问题与打开图像文件有关.在我的应用程序中,用户使用他们选择的相机应用程序拍摄图像,然后我对返回的图像进行操作.根据手机,Android版本和所选的相机应用程序,我在onActivityResult中返回不同的参数.有时我会得到一个URI,有时只是一个图像,有时两者都有.

启动相机的代码是:

Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_IMAGE); 
Run Code Online (Sandbox Code Playgroud)

然后我收到结果:

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");
        }
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

当我获得URI而不是图像时,我的问题出现了.如果imageBmp为null,那么我需要从URI加载图像.我已经测试了几个设备/应用程序组合.有时,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);
...
Run Code Online (Sandbox Code Playgroud)

如果它在内部存储上,那么我得到一个FileNotFoundException.

我的具体问题是:如何修改此文件以独立于文件系统的位置打开文件,只知道URI?我想做的事情如下:

File imageFile = new File(imageUri);
Run Code Online (Sandbox Code Playgroud)

但是File不接受Uri对象.我执行托管查询将其转换为String.

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

nan*_*esh 8

您必须使用contentResolver来访问以uri身份传递的内部文件

ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(imageUri);
Run Code Online (Sandbox Code Playgroud)