我正在编写一个应用程序,当您单击按钮时,它会打开 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 文档”。这让我抓狂。我是否正确访问该文件?有任何想法吗?谢谢
您必须将 pdf 从 asset 文件夹复制到 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)