Android中WiFi文件下载时的下载速度及剩余时间计算方法
实现实时下载速度与剩余时间计算的修改方案
修改后的完整代码
private String downloadFile(String MY_URL) { int count; // 新增变量用于计算下载速度和剩余时间 long lastTime = System.currentTimeMillis(); long lastTotal = 0; try { URL url = new URL(MY_URL); URLConnection connection = url.openConnection(); connection.connect(); long startTime = System.currentTimeMillis(); int lengthOfFile = connection.getContentLength(); InputStream input = new BufferedInputStream(url.openStream(), 8192); fileName = MY_URL.substring(MY_URL.lastIndexOf('/') + 1, MY_URL.length()); File outputFile = new File(directory, fileName); OutputStream output = new FileOutputStream(outputFile); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { if (isCancelled) { return null; } else { total += count; int status = (int) ((total * 100) / lengthOfFile); output.write(data, 0, count); // 计算实时下载速度与剩余时间 long currentTime = System.currentTimeMillis(); long timeDiff = currentTime - lastTime; if (timeDiff >= 1000) { // 每秒更新一次,避免UI频繁刷新 long bytesDiff = total - lastTotal; // 计算速度,单位转换为MB/s(可改为KB/s) double speed = (bytesDiff / 1024.0 / 1024.0) / (timeDiff / 1000.0); // 计算剩余字节数 long remainingBytes = lengthOfFile - total; // 计算剩余时间,避免除以0 long remainingTime = speed > 0 ? (long) (remainingBytes / 1024.0 / 1024.0 / speed) : 0; // 更新UI handler.post(() -> { progress_circular_id.setProgress(status); textview_progress_status_id.setText(String.valueOf(status) + "%"); // 显示下载速度,保留1位小数 textview_speed.setText(String.format("%.1f MB/s", speed)); // 格式化剩余时间为时分秒 String remainingTimeStr = String.format("%02d:%02d:%02d", remainingTime / 3600, (remainingTime % 3600) / 60, remainingTime % 60); textview_remaining_time.setText("剩余时间: " + remainingTimeStr); if (status == 100) { dialog.dismiss(); } }); // 更新记录的时间和字节数 lastTime = currentTime; lastTotal = total; } } } appSharedPreferences.setStatusFileDownloading(false); output.flush(); output.close(); input.close(); return "Downloaded at: " + directory.getPath() + fileName; } catch (IOException e) { Log.e("Abhan", "Error: " + e.getLocalizedMessage()); runOnUiThread(() -> customLoader.hide()); } customLoader.hide(); return "Downloading Error"; }
关键改动说明
- 新增
lastTime和lastTotal变量,记录上一次计算速度的时间点与对应已下载字节数。 - 每秒触发一次速度计算:通过时间差内的下载字节量,转换为MB/s(可根据需求调整为KB/s)。
- 剩余时间计算:用剩余字节数除以当前下载速度,转换为秒后格式化为时分秒的友好显示。
- 需提前在布局中添加两个TextView(
textview_speed和textview_remaining_time)用于展示速度与剩余时间。 - 加入速度为0的判断,避免出现除以0的异常。
内容的提问来源于stack exchange,提问作者MARSH
相关产品推荐
相关产品推荐

