android-如何从res / raw文件夹打开PDF文件?
作者:互联网
我正在编写一个在单击按钮时打开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从资产文件夹复制到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);
}
}
标签:android,pdf,android-resources,android-intent 来源: https://codeday.me/bug/20191011/1894451.html