Android下载管理DownloadManager介绍和使用封装

  • DownloadManager简单介绍
    DownloadManager是系统开放给第三方应用使用的类,包含两个静态内部类DownloadManager.Query和DownloadManager.Request。DownloadManager.Request用来请求一个下载,DownloadManager.Query用来查询下载信息。

先上DownloadManager的用法:

DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
String downUrl = "http://xxxx.apk";// 下载的地址 URL
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));//创建 request 对象
request.setDestinationInExternalPublicDir("test", "demo.apk");//设置下载目录和名字,这里目录没有不存在的话需要自行创建,不然会出异常 IllegalStateException
request.setTitle("test");// 通知栏的标题
request.setDescription("下载中");// 通知栏的内容
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);// 设置通知栏是否显示
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);// 设置联网的方式,分为WiFi下载,和移动手机网络,默认是联网就下载
request.setMimeType("application/vnd.android.package-archive");// 设置下载内容的 mimetype,可以自定义
request.addRequestHeader("Content-Type", "text/xml");// 添加 请求头
long downloadId = downloadManager.enqueue(request);// 开始下载

setNotificationVisibility的取值有如下方式,
这里写图片描述

setAllowedNetworkTypes的取值有如下方式,
这里写图片描述

调用downloadManagerenqueue接口进行下载,返回唯一的downloadId。然后需要监听下载的进度,我们创建一个内容观察者来监听Uri.parse(“content://downloads/my_downloads”)下载的内容,
- 下载进度监听

    public class DownloadChangeObserver extends ContentObserver {
    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    private Handler handler;
    public DownloadChangeObserver(Handler handler) {
        super(handler);
        this.handler = handler;
    }

    @Override
    public void onChange(boolean selfChange) {
        updateView();
    }

    public void updateView() {
        handler.sendMessage(handler.obtainMessage(0));
    }

}

然后我们用 handler 发送消息来通知内容更新,我们通过下面方法来拿到下载的进度。

public int[] getBytesAndStatus(long downloadId) {
        int[] bytesAndStatus = new int[] {-1, -1, 0};
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = null;
        try {
            c = downloadManager.query(query);
            if (c != null && c.moveToFirst()) {
                bytesAndStatus[0] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                bytesAndStatus[1] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                bytesAndStatus[2] = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return bytesAndStatus;
    }
  • 下载成功监听
    下载完成后,下载管理会发出DownloadManager.ACTION_DOWNLOAD_COMPLETE这个广播,并传递downloadId作为参数。通过接受广播我们可以打开对下载完成的内容进行操作。代码如下:
public class DownLoadReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            // get complete download id
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            // to do here
            Uri uriForDownloadedFile = downloadManager.getUriForDownloadedFile(completeDownloadId);
            Intent installIntent = new Intent(Intent.ACTION_VIEW);
            installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 授予目录临时共享权限
            installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            installIntent.setDataAndType(uriForDownloadedFile, "application/vnd.android.package-archive");
            mContext.startActivity(installIntent);
        }
    }

然后如果我们在 Activity 使用的话记得在退出 activity 的时候注销广播和内容观察者,避免内存泄漏。

 public void cancel() {
        if (downLoadReceiver != null) {
            mContext.unregisterReceiver(downLoadReceiver);
        }

        if (downloadChangeObserver != null) {
            mContext.getContentResolver().unregisterContentObserver(downloadChangeObserver);
        }
    }

最后加个封装的 DownloadManager 的类,地址链接

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值