安卓下载管理器

7
4个回答

21

您可以使用DownloadManager.Request对象配置此类信息。在本教程中,Request对象在onClick()中被创建和使用。

例如:

DownloadManager.Request req=new DownloadManager.Request(uri);

req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
                               | DownloadManager.Request.NETWORK_MOBILE)
   .setAllowedOverRoaming(false)
   .setTitle("Demo")
   .setDescription("Something useful. No, really.")
   .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                      "test.mp4");

(以上代码来自此示例项目


1
最后一行是最重要的 :) 起初我在那方面有些困难。 - Dominik Mohr
嗨,CommonsWare,我仍然不确定如何告诉DownloadManager将文件存储在哪个文件夹中:(。就像在Async中所做的那样 OutputStream output = new FileOutputStream("/sdcard/Myfolder/file_name.extension"); - Mich
@Mich:setDestinationInExternalPublicDir()及其相关方法允许您将输出目录指定为File,而不是OutputStream - CommonsWare
@CommonsWare 如果我想将目标更改为我的应用程序数据库文件夹,我该怎么做?我已经尝试过这段代码.setDestinationUri(dst_uri);但是它会出现错误**Caused by: java.lang.IllegalArgumentException: Not a file URI:**。 - mehmet
@mehmet:getExternalStoragePublicDirectory()不接受路径作为参数。 - CommonsWare
显示剩余3条评论

5

CommonsWare的回答中最后一行指出了目的地。他只是使用SD卡上的常规下载文件夹,但你也可以这样做:

req.setDestinationInExternalPublicDir("/mnt/sdcard/Myfolder", "file_name.extension");

2
使用req.setDestinationUri(uri)或req.setDestinationInExternalPublicDir的缺点是什么? - Mich
7
您也可以使用 Environment.getExternalStorageDirectory() 替代硬编码的 **"/mnt/sdcard"**。 - Kalarani

2
你需要确保用户为你的应用程序允许外部存储器访问权限。在下载时,请包含以下代码:
Original Answer 翻译成“最初的回答”。
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
     Uri uri = Uri.parse(url_string);
     DownloadManager.Request request = new DownloadManager.Request(uri);        
     request.setVisibleInDownloadsUi(true);        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    // include this line if permission has been granted by user to external directory
     request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, uri.getLastPathSegment());  
// or this line if not yet granted
request.setDestinationUri(Uri.parse("file://" + uri.getLastPathSegment());      
    Long reference = downloadManager.enqueue(request); 

0

您可以尝试以下操作:

  1. 访问该网址了解有关下载管理器的信息https://github.com/quoraboy/DownloadManagerInAndroid
  2. 据我所知,您无法手动暂停/恢复下载。
  3. 如果您取消下载,则完全取决于您的服务器是否支持暂停/恢复功能。如果是,则在取消下载后,如果您重新开始下载,则可能实际上会恢复下载,而不是从头开始下载。

用户可以在“下载管理器”中暂停和恢复下载。 - Devrath

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接