2016-04-21 95 views
0
DownloadManager.Request request = new DownloadManager.Request(uri); 
     request.setDestinationInExternalPublicDir(Environment. 
         DIRECTORY_DOWNLOADS, nameOfFile) 

要打开它下载后如何打开下载的文件?

 File file = new File(Environment. 
        DIRECTORY_DOWNLOADS, nameOfFile); 
      MimeTypeMap map = MimeTypeMap.getSingleton(); 
      String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName()); 
      String type = map.getMimeTypeFromExtension(ext); 

但我得到该文件不能accessed.Check位置的错误消息

+0

你有所需的权限下载你的文件? – camelCaseCoder

+0

是的我有<使用权限android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/> <使用权限android:name =“android.permission.ACCESS_DOWNLOAD_MANAGER”/> @camelCaseCoder –

+0

好吧,文件路径是否正确?你在Android 6上测试这个吗? – camelCaseCoder

回答

1

尝试使用读取权限:

android.permission.READ_EXTERNAL_STORAGE 
+0

没有得到相同的错误 –

0

尝试这样...

protected void openFile(String fileName) { 
    Intent install = new Intent(Intent.ACTION_VIEW); 
    install.setDataAndType(Uri.fromFile(new File(fileName)), 
      "MIME-TYPE"); 
    startActivity(install); 
} 
+0

你也可以在这里看到一个例子https://github.com/commonsguy/cw-android/blob/master/Internet/Download/src/ com/commonsware/android/download/DownloadDemo.java –

+0

我已经创建了一个dir最终文件folder = new File(Environment.getExternalStorageDirectory()+“Wonders”);布尔成功= true; if(!folder.exists()){ success = folder.mkdir();如何设置路径request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,****** here **** ,nameOfFile)@saurabh gupta –

0

这是一个工作解决方案。注意:不要使用DownloadManager.COLUMN_LOCAL_FILENAME,因为它在API 24中不推荐使用。请改用DownloadManager.COLUMN_LOCAL_URI。

  1. 创建字段downlaod manager和一个长变量来保存下载ID。

    DownloadManager dm; 
    long downloadId; 
    String pendingDownloadUrl = url; 
    fial int storagePermissionRequestCode = 101; 
    
  2. 创建下载管理器 dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

  3. 注册广播接收器下载完整

    BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() { 
        @Override 
        public void onReceive(final Context context, final Intent intent) { 
         Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId)); 
         if (c != null) { 
          c.moveToFirst(); 
          try { 
           String fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); 
           File mFile = new File(Uri.parse(fileUri).getPath()); 
           String fileName = mFile.getAbsolutePath(); 
           openFile(fileName); 
          }catch (Exception e){ 
           Log.e("error", "Could not open the downloaded file"); 
          } 
         } 
        } 
    };  
    

//注册boradcast下载完整

registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
  • 开始下载
  • 开始下载

    private void onDownloadStart(String url) { 
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { 
        downloadFile(url); 
    } else { 
        pendingDownloadUrl = url; 
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, storagePermissionRequestCode); 
    } } 
    

    //下载文件使用下载管理器

    private void downlaodFile(String url){ 
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); 
        String filename = URLUtil.guessFileName(url, null, null); 
        request.allowScanningByMediaScanner(); 
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename); 
        downloadId = dm.enqueue(request);//save download id for later reference } 
    

    //权限状态

    @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
        if(requestCode == storagePermissionRequestCode){ 
         boolean canDownload = true; 
         for (int grantResult : grantResults) { 
          if (grantResult == PackageManager.PERMISSION_DENIED) { 
           canDownload = false; 
           break; 
          } 
         } 
         if(canDownload){ 
          downlaodFile(pendingDownloadUrl); 
         } 
        }  } 
    
  • 打开下载的文件

    private void openFile(String file) { 
    try { 
        Intent i = new Intent(Intent.ACTION_VIEW); 
        i.setDataAndType(Uri.fromFile(new File(file)), "application/pdf");//this is for pdf file. Use appropreate mime type 
        startActivity(i); 
    } catch (Exception e) {   
        Toast.makeText(this,"No pdf viewing application detected. File saved in download folder",Toast.LENGTH_SHORT).show(); 
    } 
    }
  • 现在尝试通过调用downladFile(String url);方法