Android中使用DownloadManager进行下载操作

来源:互联网 发布:java assert 编辑:程序博客网 时间:2024/06/07 02:10

前言

本文介绍对DownloadManager的使用,即实战教程。由于代码量不大,就不托管了,把主要代码直接贴在了下面。

Download Manager引进于API Level9(android2.3)。DownLoadManager可以实现对Http连接,监控链接变化,下载状态等。
DownLoadManager是一个系统服务,可以通过应用上下文获取,getSystemService(DOWNLOAD_SERVICE)获得:

DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

开启权限

另外,也是最重要的一点,记得开启网络请求权限哦!

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

创建Request

Uri downUri = Uri.parse(url);DownloadManager.Request request = new DownloadManager.Request(downUri);

此时Request创建完成。DownLoadManager会在下载时在通知栏显示下载进度。可以通过request对下载进度条的样式进行设置。

设定Notification

//自定义通知,设置在将Request设置进队列之前,否则无效。        request.setTitle("weixin");        request.setDescription("现在我的文件正在下载.....");        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

其中request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);方法是对Notification的显隐状态进行设定。
状态类型有以下几个:

设定下载路径

request.setDestinationInExternalFilesDir();        request.setDestinationInExternalPublicDir();        request.setDestinationUri();

开启下载

long reference = downloadManager.enqueue(request);//获取的reference实际上就是下载任务的id,可以通过该id对下载进行操作,包括状态监听,查询,溢出等

查询下载

 Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(reference));

对于Cursor不是太了解的同学,可以百度一下。
这里说明一下,DownLoadManager的Cursor的参数:

DownloadManager的一些Intent

Broadcast的Intent:

  • ACTION_DOWNLOAD_COMPLETE:当下载完毕时由DownloadManager发送的广播。携带的信息:EXTRA_DOWNLOAD_ID
  • ACTION_NOTIFICATION_CLICKED:当用户点击正在运行的下载时(Notification)由DownloadManager发出的广播。携带的信息EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS

开启Activity的Intent:

  • ACTION_VIEW_DOWNLOADS:将会打开一下展示所有下载的Activity。可以携带的extra是INTENT_EXTRAS_SORT_BY_SIZE
0 0