簡體   English   中英

使用意圖打開本地PDF文件

[英]Using an Intent to open a local PDF file

我已經在互聯網上搜索了一段時間,但沒有找到解決方案!

在我的項目中,我將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();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM