【发布时间】:2017-03-07 09:58:45
【问题描述】:
我正在尝试制作一个允许用户从手机打开 PDF 文件的 PDF 阅读器。
我首先创建一个允许我浏览文件的意图
Intent openFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
openFileIntent.setType("*/*");
startActivityForResult(openFileIntent, FILE_OPEN_CODE);
这是 onActivityResult:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_OPEN_CODE && resultCode == RESULT_OK && data != null){
Uri selectedFile = data.getData();
try {
openFile(selectedFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
获得 Uri 后,我将其发送到打开 PDF 的方法:
public void openFile(Uri fileUri) throws IOException {
final int WIDTH = viewPDF.getWidth();
final int HEIGHT = viewPDF.getHeight();
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + fileUri.getPath();
Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_4444);
File pdfFile = new File(filePath);
Toast.makeText(getApplicationContext(), "Opened: " + filePath, Toast.LENGTH_LONG).show();
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
currentPage = 0;
Matrix matrix = viewPDF.getImageMatrix();
Rect rect = new Rect(0, 0, WIDTH, HEIGHT);
renderer.openPage(currentPage).render(bitmap, rect, matrix, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
viewPDF.setImageMatrix(matrix);
viewPDF.setImageBitmap(bitmap);
}
现在,问题是我收到以下错误:
W/System.err: java.io.FileNotFoundException: No such file or directory
我确定该文件存在,但我从 Uri 获取的路径如下
/storage/emulated/0/document/2443
2443 是我得到的文件名而不是“MY_FILE.pdf” 我需要能够获取文件名才能在渲染器上打开 pdf
另外,我已经在清单中声明了权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
并且还手动提示输入 android M 及更高版本的权限
【问题讨论】:
-
but the path that i get from the Uri is the following /storage/emulated/0/document/2443。这就是 uri.getPath() 的值。但是你最好看一下通过 uri.toString() 获得的内容方案。 -
介意再详细说明一下吗?
-
如果我尝试得到 content://com.android.providers.downloads.documents./document/2443
-
所以你看到你有一个内容方案。不是文件系统路径。
标签: android pdf uri android-internal-storage