我正在编写一个应用程序,当您单击按钮时会打开一个pdf文件。以下是我的代码:
File pdfFile = new File(
"android.resource://com.dave.pdfviewer/"
+ R.raw.userguide);
Uri path = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
startActivity(intent);
然而,当我运行它并按下按钮时,它显示“文档无法打开,因为它不是有效的PDF文档”。这让我很生气。我是否正确访问了该文件?有任何想法吗?感谢
答案 0 :(得分:5)
您必须将pdf从assets文件夹复制到sdcard文件夹。
.....
copyFile(this.getAssets().open("userguide.pdf"), new FileOutputStream(new File(getFilesDir(), "yourPath/userguide.pdf")));
File pdfFile = new File(getFilesDir(), "yourPath/userguide.pdf"); Uri path = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
答案 1 :(得分:-1)
您可以将您的pdf插入android中的资源文件夹中,然后尝试使用:
File pdfFile = new File(getAsset().open("userguide.pdf"));
Uri path = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
startActivity(intent);
修改强> 文件夹资产中的URi是:file:/// android_asset / RELATIVE_PATH 然后来源将是:
File pdfFile = new File("file:///android_asset/userguide.pdf");
Uri path = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
startActivity(intent);