2016-04-21 87 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);方法