我想我的应用程序来打开PDF我的、我想、应用程序、PDF

2023-09-06 16:47:16 作者:梦醒心亦碎丶

我的应用程序downlods从一个链接,将其保存到SD卡的PDF文件,并​​且它的正常工作..但什么我struggeling的就是我不能让我的应用程序查看PDF文件。(尽管我在我的模拟器安装PDF阅读器)没有下载文件后会发生......这里是我的code为开扩PDF文件

 的InputStream输入=新的BufferedInputStream(url.openStream());            文件SD卡= Environment.getExternalStorageDirectory();            文件DIR =新的文件(sdCard.getAbsolutePath()                    +/ MyApp的/下载);            dir.mkdirs();            档案文件=新的文件(目录应用程序/ PDF格式);            FileOutputStream中输出=新的FileOutputStream(文件); 

解决方案

使用低于code打开PDF文件。

 文件pdfFile =新的文件(到/ mnt / SD卡/文件路径/ yourpdf.pdf);    如果(pdfFile.exists()){        URI路径= Uri.fromFile(pdfFile);        意图pdfIntent =新意图(Intent.ACTION_VIEW);        pdfIntent.setDataAndType(路径,应用程序/ PDF格式);        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        尝试{           startActivity(pdfIntent);        }赶上(ActivityNotFoundException E){           Toast.makeText(yourActivityClass.this,没有可用来查看PDF应用程序,Toast.LENGTH_LONG).show();        }    }其他{        Toast.makeText(yourActivityClass.this,找不到文件,Toast.LENGTH_LONG).show();    } 
PDF文件突然打不开,点击属性显示打开方式为 未知应用程序,怎么才能改回PDF文件

yourActivityClass.this 是应用程序上下文使其正确而高于code测试。

my app downlods a pdf file from a link saving it to SD card, and it's working fine.. but what I'm struggeling at is I couldn't let my app views the pdf file..( although I've installed PDF viewer on my emulator)nothing happens after downloading the file... here's my code for openning the pdf file

                                   InputStream input = new BufferedInputStream(url.openStream());
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File(sdCard.getAbsolutePath()
                    + "/myapp/download");
            dir.mkdirs();
            File file = new File(dir, "application/pdf");
            FileOutputStream output = new FileOutputStream(file);

解决方案

Use below code to open pdf file.

File pdfFile = new File("/mnt/sdcard/path_to_file/yourpdf.pdf"); 
    if(pdfFile.exists()) {
        Uri path = Uri.fromFile(pdfFile); 
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
           startActivity(pdfIntent);
        } catch(ActivityNotFoundException e) {
           Toast.makeText(yourActivityClass.this, "No Application available to view pdf", Toast.LENGTH_LONG).show(); 
        }
    } else {
        Toast.makeText(yourActivityClass.this, "File not found", Toast.LENGTH_LONG).show(); 
    }

yourActivityClass.this is application context make it correct while testing above code.