Android 计算网络速度&文件下载剩余时间<<最优方案>>-爱代码爱编程
最近在项目开发中遇到了一项功能,需要在下载文件时显示出当前的网络速度和预计剩余时间,在调研中发现使用的比较多的是通过TrafficStats来获取网络使用量然后在间隔每秒后重新获取一次网络使用量,两者相机算既可以得出每秒的网络使用量。
public class FlowStats {
private long lastTotalRxBytes;
private long lastTimeStamp;
public String getNetSpeedToMB(Context context){
String netSpeed;
long speed = absKb(context);
if (speed == 0){
return "0 MB/s";
}
netSpeed = String.format("%.2f", new Float(speed / 1024f)) + " MB/s";
return netSpeed;
}
public String getNetSpeedToKB(Context context){
String netSpeed;
long speed = absKb(context);
netSpeed = speed + " KB/s";
return netSpeed;
}
private long absKb(Context context){
try{
long nowTotalRxBytes = TrafficStats.getTotalRxBytes() / 1024; // kb
long nowTimeStamp = System.currentTimeMillis();
long speed = (nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp);
lastTotalRxBytes = nowTotalRxBytes;
lastTimeStamp = nowTimeStamp;
return speed;
}catch (Exception e){
System.out.println(e.getMessage());
return 0;
}
}
}
这种方案虽然可以得到结果,但获取的是总量,其中也包含了非本应用的使用量,这样计算出的结果是没法用的。其次可以只获取本应用的使用量,但这样获取出的结果无法精确到单个文件的速度所以也没法直接使用。
最优方案:
byte[] buffer = new byte[1024*4];
int len;
long beforeTime = System.currentTimeMillis(); // 前一秒
long secondCount = 0; // 每秒的下载量
while ((len = inputStream.read(buffer)) != -1) {
// 计算每秒的下载量并进行回调
long currentTime = System.currentTimeMillis();
if (currentTime - beforeTime > 1000){
beforeTime = currentTime;
info.setSecondCount(secondCount);
secondCount = 0;
HttpDownloadManager.getInstance().notifyDownloadProgressed(info);
}else {
secondCount += len;
}
}
上面是通过在读取文件流时按每秒中读取的量来回调给观察者 下面在看观察者收到回调后的处理
@Override
public void onDownloadProgressed(DownLoadInfo info) {
this.downLoadInfo = info;
long secondCount = info.getSecondCount();
float m = secondCount / 1024f / 1024f;
int surplus = (int) ((info.getCountLength() - info.getReadLength()) / secondCount);
setText(String.format("%.1f", m) + "MB/s 剩余时间" + surplus + "秒 已下载 " + info.getPercentage() + "%");
}
呈现效果
Demo地址:netSpeedDemo
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/qq_35624842/article/details/111040677