title: Measuring Download Speed with Java/Android
body: <p>I am working on an Android app where I need to, as accurately as possible, measure the download speed of the current connection. Here's the best method I could find so far (basically I start a timer, start downloading a Linux distro from a fast server, download around 200 kbytes, then stop the timer and check time elapsed and total bytes downloaded): </p>
  
  <pre><code>try{                
      InputStream is = new URL("http://www.domain.com/ubuntu-linux.iso").openStream();
      byte[] buf = new byte[1024];
      int n = 0;              
      startBytes = TrafficStats.getTotalRxBytes(); /*gets total bytes received so far*/
      startTime = System.nanoTime();
      while(n&lt;200){
          is.read(buf);
          n++;                
      }
      endTime = System.nanoTime();
      endBytes = TrafficStats.getTotalRxBytes(); /*gets total bytes received so far*/
      totalTime = endTime - startTime;
      totalBytes = endBytes - startBytes;
  }
  catch(Exception e){
      e.printStackTrace();
  }   
  </code></pre>
  
  <p>After that I just need to divide the number of bytes transferred by the time taken and it will give the download speed in bps.</p>
  
  <p><strong>Questions</strong>: 
  1. Will this method be accurate?
  2. Do you know a better one?</p>
  
  <p>Thanks a lot.</p>