Android 监听下载进度

本文介绍如何在Android应用中实现仅限WIFI条件下进行的大文件下载功能,包括设置下载请求、配置下载参数及查询下载进度的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private DownloadManager downloadManager;

private long Id;

downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
// 假设从这一个链接下载一个大文件。
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(Config.apkUrl));
// 仅允许在WIFI连接情况下下载
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
// 通知栏中将出现的内容
request.setTitle("我的下载");
request.setDescription("下载一个大文件");
// 下载过程和下载完成后通知栏有通知消息。
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// 此处可以由开发者自己指定一个文件存放下载文件。
// 如果不指定则Android将使用系统默认的
// request.setDestinationUri(Uri.fromFile(new File("")));
// 默认的Android系统下载存储目录
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "my.apk");
// enqueue 开始启动下载...
Id = downloadManager.enqueue(request);



// 查询下载进度,文件总大小多少,已经下载多少?
private void query() {
    Log.e("MainActivity", "query");
    DownloadManager.Query downloadQuery = new DownloadManager.Query();
    downloadQuery.setFilterById(Id);
    Cursor cursor = downloadManager.query(downloadQuery);
    if (cursor != null && cursor.moveToFirst()) {
        int fileName = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
        int fileUri = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
        String fn = cursor.getString(fileName);
        String fu = cursor.getString(fileUri);
        int totalSizeBytesIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
        int bytesDownloadSoFarIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
        // 下载的文件总大小
        int totalSizeBytes = cursor.getInt(totalSizeBytesIndex);
        // 截止目前已经下载的文件总大小
        int bytesDownloadSoFar = cursor.getInt(bytesDownloadSoFarIndex);
        Log.e(this.getClass().getName(), "from " + fu + " 下载到本地 " + fn + " 文件总大小:" + totalSizeBytes + " 已经下载:" + bytesDownloadSoFar);
        cursor.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值