【问题标题】:How to download file from URL in android?如何从Android中的URL下载文件?
【发布时间】:2020-07-26 11:29:23
【问题描述】:

从 url 下载文件的最佳方式是什么。我尝试使用下载管理器。但我不明白如何获取下载文件的 Uri 。这是我的代码:

   file?.let {
            val uri = Uri.parse(it)
            val downloadManager = getSystemService<Any>(Context.DOWNLOAD_SERVICE) as DownloadManager?
            val request = DownloadManager.Request(uri)
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or
                    DownloadManager.Request.NETWORK_MOBILE)
            request.allowScanningByMediaScanner()
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "downloadfileName")
            request.setMimeType("*/*")
            downloadManager?.enqueue(request)
        }

也许今天有更好的方法来下载文件并获取 Uri。请帮帮我

【问题讨论】:

    标签: android kotlin uri android-download-manager


    【解决方案1】:

    如何从 Url 下载文件

    fun downloadPdf(baseActivity:Context,url: String?,title: String?): Long {
            val direct = File(Environment.getExternalStorageDirectory().toString() + "/your_folder")
    
            if (!direct.exists()) {
                direct.mkdirs()
            }
            val extension = url?.substring(url.lastIndexOf("."))
            val downloadReference: Long
             var  dm: DownloadManager
             dm= baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            val uri = Uri.parse(url)
            val request = DownloadManager.Request(uri)
            request.setDestinationInExternalPublicDir(
                    "/your_folder",
                    "pdf" + System.currentTimeMillis() + extension
            )
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            request.setTitle(title)
            Toast.makeText(baseActivity, "start Downloading..", Toast.LENGTH_SHORT).show()
    
            downloadReference = dm?.enqueue(request) ?: 0
    
            return downloadReference
    
        }
    

    在调用此方法之前,请检查运行时权限:

    Manifest.permission.WRITE_EXTERNAL_STORAGE
    

    【讨论】:

      【解决方案2】:

      请试试这个代码

      public void downloadPdf(String url, String sem, String title, String branch) {
      Uri Download_Uri = Uri.parse(url);
      DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
      
      //Restrict the types of networks over which this download may proceed.
      request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
      //Set whether this download may proceed over a roaming connection.
      request.setAllowedOverRoaming(false);
      //Set the title of this download, to be displayed in notifications (if enabled).
      request.setTitle("Downloading");
      //Set a description of this download, to be displayed in notifications (if enabled)
      request.setDescription("Downloading File");
      //Set the local destination for the downloaded file to a path within the application's external files directory
      request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title + "_" + branch + "_" + sem + "Year" + System.currentTimeMillis() + ".pdf");
      
      request.allowScanningByMediaScanner(); 
      request. setNotificationVisibility(DownloadManager.Request. VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION)
      
      //Enqueue a new download and same the referenceId
      downloadReference = downloadManager.enqueue(request);
      
      }
      

      附加广播接收器

      BroadcastReceiver attachmentDownloadCompleteReceive = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();
          if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
              long downloadId = intent.getLongExtra(
                      DownloadManager.EXTRA_DOWNLOAD_ID, 0);
              openDownloadedAttachment(context, downloadId);
          }
      }
      };
      
      
      private void openDownloadedAttachment(final Context context, final long downloadId) {
      DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
      DownloadManager.Query query = new DownloadManager.Query();
      query.setFilterById(downloadId);
      Cursor cursor = downloadManager.query(query);
      if (cursor.moveToFirst()) {
          int downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
          String downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
          String downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
          if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
              openDownloadedAttachment(context, Uri.parse(downloadLocalUri), downloadMimeType);
          }
      }
      cursor.close();
      } 
      

      【讨论】:

      • 感谢您的回答。但是我怎样才能得到下载文件的 Uri 呢?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      相关资源
      最近更新 更多