2015-01-12 20 views
1

在我的應用程序中,我想將PDF文件存儲在資產中,並且當按下查看按鈕時,應該通過安裝在設備中的第三方應用程序查看PDF。從assests文件夾中訪問pdf文件

通過使用下面的代碼,我試圖訪問資產文件夾內的PDF文件,但應用程序說'文件不可用'。我搜索了各種代碼的stackoverflow,他們都沒有工作。但是當我試圖提取APK文件時,我可以看到資產文件夾內的PDF文件。

以下是我試過的代碼:

File file = new File("file://" + getFilesDir() + "/ccv.pdf"); 

      if (file.exists()) { 

       Uri path = Uri.fromFile(file); 
       Intent intent = new Intent(Intent.ACTION_VIEW); 
       intent.setDataAndType(path, "application/pdf"); 
       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

       try { 
        startActivity(intent); 
       } 
       catch (ActivityNotFoundException e) { 
        Toast.makeText(home.this, 
         "No Application Available to View PDF", 
         Toast.LENGTH_SHORT).show(); 
       } 
      } 
      else 
      { 
       Toast.makeText(home.this, 
         "File not available", 
         Toast.LENGTH_SHORT).show(); 
      } 

所以,請提供代碼段訪問資源文件夾內的PDF文件。

在此先感謝

回答

1
Try this 

File file = new File("file:///android_asset" + "/ccv.pdf"); 

      if (file.exists()) { 

       Uri path = Uri.fromFile(file); 
       Intent intent = new Intent(Intent.ACTION_VIEW); 
       intent.setDataAndType(path, "application/pdf"); 
       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

       try { 
        startActivity(intent); 
       } 
       catch (ActivityNotFoundException e) { 
        Toast.makeText(home.this, 
         "No Application Available to View PDF", 
         Toast.LENGTH_SHORT).show(); 
       } 
      } 
      else 
      { 
       Toast.makeText(home.this, 
         "File not available", 
         Toast.LENGTH_SHORT).show(); 
      } 
+0

對不起訪問!不工作..仍然「文件不可用」 – user3421325

+0

你把你的PDF文件放在文件夾或直接在資產或請嘗試使用直接鏈接在意圖 –

+0

我已經把文件放在資產文件夾。這裏是截圖:http://tinypic.com/r/2yvw7kk/8 – user3421325

0

最後我能找到答案,資產不能使用File(文件),它不僅可以使用Assetmanager

AssetManager assetManager = getAssets(); 
InputStream ims = assetManager.open("ccv.pdf"); 
+1

接受您自己的答案,這對其他人很有用。 – Sushant

相關問題