如何在 onActivityResult 回调中从 PDF 选择器意图库获取的 pdfUri 获取文件路径?

How to get File path from pdfUri obtained from PDF chooser intent library, in onActivityResult call back?

参考同一类别中提出的问题,并作为其扩展:

(How to get the file path from a URI that points to a PDF document?)

我的问题:

在我的 HTC 816 Desire phone [注意:此设备已升级到 MarshMallow,但仍然有 KitKat 崩溃。作为一名开发人员,我有过这样的经历,即有意打开 Camera 以获取其捕获的图像,但从不释放其资源。这给了我一个内部崩溃,当我尝试拍摄第二张照片时。],返回的路径以 "/document/primary:" 开头,并保留在 'pdfUri.getPath()' 中,导致文件未找到异常。此外,当我在 'MediaStore.Images.Media.DATA' 中搜索时,返回的列索引为 -1。

Q1。当列索引为 -1 时,我应该简单地从文件路径中删除 "/document/primary:" 吗?因为在更高的 phones(23 及以上)中,这个 (pdfUri.getPath()) 工作正常,给了我正确的路径。

Q2。我应该从哪里获得 phone 的补丁来修复 Camera resource not releasing 错误,还有固件级别的其他错误。

也请指导我正确地提出这个问题,以防万一提出的问题不准确。

为了解决这个问题,我正在尝试执行以下操作:

  1. 我打算使代码通用,我得到的解决方案适用于 PDF 以外的许多其他文件格式:

    private String saveFileFromUri(Uri pdfUri){
        try{
            InputStream is=
            baseActivity.getContentResolver().openInputStream(pdfUri);
            byte[]bytesArray=new byte[is.available()];
            int read=is.read(bytesArray);
        //write to sdcard
    
        File dir=new File(Environment.getExternalStorageDirectory(),"/PRJ");
        boolean mkdirs=dir.mkdirs();
        File myPdf=new 
        File(Environment.getExternalStorageDirectory(),"/PRJ/myPdf.pdf");
        if(read==-1&&mkdirs){
    
        }
        FileOutputStream fos=new FileOutputStream(myPdf.getPath());
        fos.write(bytesArray);
        fos.close();
        //            System.out.println(fileString);
        return myPdf.getPath();
    }catch(FileNotFoundException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }
    return null;}
    
  2. 为了能够释放相机资源,我将使用基于表面视图的相机 Activity,它允许这样做。这是代码的一部分:

释放相机资源:

    @Override
public void onPause() 
{
    super.onPause();

        if (mCamera != null){
            //              mCamera.setPreviewCallback(null);
            mPreview.getHolder().removeCallback(mPreview);
            releaseMediaRecorder();
            mCamera.release();        // release the camera for other applications
            mCamera = null;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mCamera == null) {
            mCamera=getCameraInstance();
            mPreview = new CameraPreview(this.getActivity(), mCamera);
            preview.addView(mPreview);
        }
    }

快乐编码:-)