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

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值