如何从res/raw文件夹中打开PDF文件?

DMC*_*DMC 2 pdf android android-intent android-resources

我正在编写一个应用程序,当您单击按钮时打开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);
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它并按下按钮时,它显示"文档无法打开,因为它不是有效的PDF文档".这让我很生气.我是否正确访问了该文件?有任何想法吗?谢谢

Jc *_*rro 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)