使用TrafficStats类时计算的下载速度是错误的

时间:2016-03-20 14:49:32

标签: java android networking network-traffic

我想构建android下载速度测试。为此,我使用TrafficStats类。问题是我得到了错误的结果。当我运行测试时,结果几乎相同,但在运行测试之前,我在Internet连接上加载了很多负载。我下载文件30秒,之后(或下载文件时),然后使用TrafficStats

计算字节

有人知道问题出在哪里吗?

这是我正在使用的代码:

@Override
        protected String doInBackground(String... urls) {
            String downloaded ="";
           // String uploaded = "";
            try{

                long BeforeTime = System.currentTimeMillis();
                long TotalTxBeforeTest = TrafficStats.getTotalTxBytes();
                long TotalRxBeforeTest = TrafficStats.getTotalRxBytes();
                URL url = new URL(urls[0]);
                URLConnection connection = new URL(urls[0]).openConnection();
                connection.setUseCaches(false);
                connection.connect();
                InputStream input = connection.getInputStream();

                BufferedInputStream bufferedInputStream = new BufferedInputStream(input);
                byte[] buffer = new byte[1024];
                int n = 0;
                long endLoop = BeforeTime+30000;
                while(System.currentTimeMillis() < endLoop) {
                  /*  if (bufferedInputStream.read(buffer) != -1){
                        break;
                    }*/
                }
                long TotalTxAfterTest = TrafficStats.getTotalTxBytes();
                long TotalRxAfterTest = TrafficStats.getTotalRxBytes();
                long AfterTime = System.currentTimeMillis();

                double TimeDifference = AfterTime - BeforeTime;
                double rxDiff = TotalRxAfterTest - TotalRxBeforeTest;
                double txDiff = TotalTxAfterTest - TotalTxBeforeTest;
                Log.e(TAG, "Download skinuto. "+ rxDiff);
                if((rxDiff != 0) && (txDiff != 0)) {
                    double rxBPS = (rxDiff / (TimeDifference/1000)); // total rx bytes per second.
                    double txBPS = (txDiff / (TimeDifference/1000)); // total tx bytes per second.
                    downloaded = String.valueOf(rxBPS) + "B/s. Total rx = " + rxDiff;
                   // uploaded = String.valueOf(txBPS) + "B/s. Total tx = " + txDiff;
                }
                else {
                    downloaded = "No downloaded bytes.";
                }
            }
            catch(Exception e){
                Log.e(TAG, "Error while downloading. "+ e.getMessage());
            }
            return downloaded;
        }

1 个答案:

答案 0 :(得分:0)

我尝试了你的代码 - 它似乎对我很好但是我改变了

while(System.currentTimeMillis() < endLoop) {
   /* if (bufferedInputStream.read(buffer) != -1) {
          break;
      }*/
}

while(System.currentTimeMillis() < endLoop) {
    if (bufferedInputStream.read(buffer) == -1){
        break;
    }
}

,如果到达流的末尾,read将返回-1