2016-06-29 163 views
3

我已經使用下載管理器下載了文件(133465.pdf),現在它存儲在手機(內部存儲器)的Downloads文件夾中。從內部存儲的下載文件夾中打開下載的文件(pdf)

我應該如何嘗試從下載文件夾中檢索下載的pdf文件?

我使用下面的代碼嘗試從下載文件夾中檢索pdf,但我在吐司上發現錯誤,說「無法顯示PDF(133465.pdf無法打開)」。

String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + "133465.pdf"; 
       Log.i("Fragmentadapter1", file); 
       File videoFile2Play = new File(file); 
       Intent i = new Intent(); 
       i.setAction(android.content.Intent.ACTION_VIEW); 
       i.setDataAndType(Uri.fromFile(videoFile2Play), "application/pdf"); 
       imageContext.startActivity(i); 

我不知道我是否使用正確的文件位置來訪問該文件。

任何幫助或建議,將不勝感激。

回答

3

如果您正在爲Lollopop和以下工作:您不必在運行時詢問用戶權限。清單權限將會執行。

如果您正在爲Marshmellow工作並且運行良好:您必須在運行時詢問用戶permission並根據用戶輸出採取行動。

記住:您還必須在Manifest上提供權限。

要下載的用戶下載文件夾中的PDF:

DownloadManager downloadmanager; 
    Environment 
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
      .mkdirs(); 

    downloadmanager = (DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE); 
    String url = hardcode + bb ; 
    Uri uri = Uri.parse(url); 
    DownloadManager.Request request = new DownloadManager.Request(uri) 
      .setTitle(bb) 
      .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, 
        bb) 
      .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
    Log.i("Download1", String.valueOf(request)); 
    downloadmanager.enqueue(request); 

Reference

,閱覽從用戶設備的下載文件夾中下載PDF:

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + 
      "YOUR FILE NAME"); 
    Uri path = Uri.fromFile(file); 
    Log.i("Fragment2", String.valueOf(path)); 
    Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW); 
    pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    pdfOpenintent.setDataAndType(path, "application/pdf"); 
    try { 
     this.startActivity(pdfOpenintent); 
    } catch (ActivityNotFoundException e) { 

    } 

注意:確保你得到了在下載查看Marshmellow和UP的PDF文件之前授予的權限。