问题
With reference to the question asked in the same category, and as an extension of this:
How to get the file path from a URI that points to a PDF document?
(How to get the file path from a URI that points to a PDF document?)
My question:
In my HTC 816 Desire phone [Note: this device is upgraded to MarshMallow but still has crashes of KitKat. As a developer, I have experienced that Camera opened by intent to get the image captured by it, never releases its resources. This gives me an internal crash, when I try to take the second picture.], the returned path is starting with "/document/primary:"
, and it is retained in 'pdfUri.getPath()'
resulting in file not found exception. Also when I search in 'MediaStore.Images.Media.DATA'
, column index returned is -1.
Q1. Should I simply remove "/document/primary:"
from the file path, when the column index comes -1. As because in higher phones (23 and above), this (pdfUri.getPath()) works OK, giving me correct path.
Q2. Where should I get the patches for my phone to fix Camera resource not releasing
bug, and there are other bugs at Firm-Ware level.
Please guide me, as well, by asking this question correctly, if in case it is not been asked accurately.
回答1:
In order to resolve the problem, I am trying to do the following:
I am going to make the code generic, that I got as a solution, for many other file formats other than 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;}
In order to be able to release Camera resource, I will use surface view based Camera Activity which allows to do that. Here is a part of the code:
Release camera resource:
@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);
}
}
Happy Coding :-)
来源:https://stackoverflow.com/questions/51999229/how-to-get-file-path-from-pdfuri-obtained-from-pdf-chooser-intent-library-in-on