【问题标题】:After download how to open downloaded file?下载后如何打开下载的文件?
【发布时间】:2017-09-21 02:09:11
【问题描述】:
    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);

但我收到一条错误消息,指出无法访问文件。请检查位置

【问题讨论】:

  • 您是否拥有所需的权限?
  • 是的,我有 @camelCaseCoder
  • 好的,文件路径是否正确?您是否在 Android 6 上对此进行了测试?
  • 不,我在 KitKat 上测试它的路径是正确的我可以看到文件
  • 你调试过,发现文件位置绝对正确,文件确实存在吗?

标签: android android-download-manager


【解决方案1】:

尝试使用读取权限:

android.permission.READ_EXTERNAL_STORAGE

【讨论】:

    【解决方案2】:

    试试这样...

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

    【讨论】:

    • 我已经创建了一个 dir final File 文件夹 = new File(Environment.getExternalStorageDirectory() + "Wonders");布尔成功=真; if (!folder.exists()) { 成功 = folder.mkdir();如何设置路径 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, ******here**** , nameOfFile)@saurabh gupta
    【解决方案3】:

    这是一个可行的解决方案。注意:不要使用 DownloadManager.COLUMN_LOCAL_FILENAME,因为它在 API 24 中已被弃用。请改用 DownloadManager.COLUMN_LOCAL_URI。

    1. 创建字段下载管理器和一个长变量来保存下载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");
                  }
              }
          }
      };      
      

    //注册广播以下载完成

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

    开始下载

    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);
            }
        }        }
    
    1. 打开下载的文件

      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();
      }
      }
    2. 现在尝试通过调用downladFile(String url); 方法下载您的文件

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 2014-05-13
      • 2013-12-07
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多