[英]How to open a PDF file from res/raw Folder?
我正在編寫一個在單擊按鈕時打開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);
}
}
您可以將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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.