当前位置: 代码迷 >> java >> 使用意图打开本地PDF文件
  详细解决方案

使用意图打开本地PDF文件

热度:40   发布时间:2023-08-04 09:30:33.0

我已经在互联网上搜索了一段时间,但没有找到解决方案!

在我的项目中,我将PDF文件放入了drawable文件夹中(老实说,我不知道将其放置在何处)。 PDF是一个菜单,向用户显示了他在那家餐厅可以找到的所有食物。 有一个按钮,使用户可以打开该PDF文件。 通过单击它,我收到一条错误消息。 它或多或少说该应用程序无法归档我的文件:“无法打开menuristorante.pdf”。

我创建了一个打开该文件的方法,这是我编写的代码:

public void openMenuRistorante(View view)
{
File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/menuristorante.pdf");
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(this, "Nessuna Applicazione per leggere i pdf", Toast.LENGTH_SHORT).show();
}
}

可能我将文件放在错误的目录中是错误的。但是,我应该在哪里放置它? 请记住,我的PDF文件必须已经在应用程序中,因此当用户安装此应用程序时,它必须在手机内。

谢谢

将PDF文件放在资产文件夹中,然后尝试使用以下代码:

Uri file= Uri.parse("file:///android_asset/mypdf.pdf");
  String mimeType =  MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(file.toString()));

try {
     Intent i;
     i = new Intent(Intent.ACTION_VIEW);
     i.setDataAndType(file,mimeType);
     startActivity(i);

} catch (ActivityNotFoundException e) {
                    Toast.makeText(this, 
                        "No Application Available to view this file type", 
                        Toast.LENGTH_SHORT).show();
                } 

我在我的应用程序中做类似的事情,尽管我的文件位于移动设备的下载文件夹中的子文件夹“ Documents”中,但我想您也可以这样做,这比将其保持在可绘制状态更好。 这是我使用的代码:

try {
            File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/Documents/" + fileName);
            Intent intent = new Intent("com.adobe.reader");
            intent.setType("application/pdf");
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(Documents.this, "Erreur d'ouverture du fichier", Toast.LENGTH_LONG).show();
        }
  相关解决方案