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(); } }