2016-06-29 37 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文件之前授予的权限。