Android学习笔记039之文件上传和下载

  文件上传和下载在我们开发中经常需要用到,现在也有很多的网络框架封装了文件上传和下载功能。不过这一篇,我们介绍一下Android系统提供的文件下载服务–DownLoadManager。在API 9之后,Android提供了Download Manager来优化和处理长时间的下载操作,在大多数情况需要用到下载文件的情况下,使用Download Manager都是一个不错的选择,并且Download Manager对于断点续传功能的支持很好。下面我们详细介绍一下DownLoadManager

DownLoadManager

  DownLoadManager在官方文档是这样描述的:

The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots. Instances of this class should be obtained through getSystemService(String) by passing DOWNLOAD_SERVICE. Apps that request downloads through this API should register a broadcast receiver for ACTION_NOTIFICATION_CLICKED to appropriately handle when the user clicks on a running download in a notification or from the downloads UI. Note that the application must have the INTERNET permission to use this class.

DownLoadManager是一个系统服务,用于处理长时间下载任务,DownLoadManager会在后台处理HTTP交互和重试下载失败或跨连接启动系统,通过getSystemService传入DOWNLOAD_SERVICE可以获得DownLoadManager的实例,可以通过注册广播接受者接收ACTION_NOTIFICATION_CLICKED来处理用户点击下载通知。使用这个下载服务需要联网的权限,所以需要在清单文件中添加如下代码:

<uses-permission android:name="android.permission.INTERNET"/>

上面是官方的介绍,DownLoadManager中有两个内部类:DownloadManager.Query和DownloadManager.Request。前者用于查询下载,后者用于设置一些请求信息。下面我们详细介绍一下这两个内部类:

DownloadManager.Request类的常用方法:
  • addRequestHeader(String header, String value):添加一个请求头

  • setAllowedNetworkTypes(int flags):设置下载时所使用的网络类型,提供的常量有:NETWORK_BLUETOOTH、NETWORK_MOBILE、NETWORK_WIFI。

  • setAllowedOverRoaming(boolean allowed):是否允许漫游

  • setDescription(CharSequence description):设置下载的描述信息

  • setDestinationInExternalFilesDir(Context context, String dirType, String subPath):设置下载文件外部存储目录

  • setDestinationUri(Uri uri):设置下载目标的URI

  • setMimeType(String mimeType):设置MIME类型

  • setShowRunningNotification(boolean show):设置是否显示下载进度提示

  • setTitle(CharSequence title):设置下载时Notificatio

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值