Search code examples
javaandroiddownloadandroid-wifi

Android - how to calculate the time needed to download a file?


In my Android application, I am using WIFI link speed to get the speed of the WIFI and get the length content of a file before downloading the file and then I am trying to get the esitmated time of download before downloading the file but the time I get is incorrect I don't know why !

that is my code to estimate the time before downloading

  URL u = new URL(url);
  HttpURLConnection c = (HttpURLConnection) u.openConnection();
  c.setRequestMethod("GET");
  c.connect();
  contentLength = Long.parseLong(c.getHeaderField("Content-Length"));
  System.out.println("content"+contentLength);
  float contentLength_float=contentLength/(float)(1000*1000);//migabyte
  float speed=((float)(mActivity.speed_wifi()))/(float)8;//convert mbps(migabit) to migabyte ps
  float sec=contentLength_float/speed;//get the sec from m/m/s

and function wifi speed ()

     public int speed_wifi()
  {
   WifiManager mainWifi;
        mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = mainWifi.getConnectionInfo();
        int speed=0;
        if(wifiInfo.getBSSID()!=null)
         {
            speed=wifiInfo.getLinkSpeed();
         }
        return speed;
  }

Solution

  • The wifi link speed you get by using that function is the maximum speed that can be achieved by the wifi in the phone, it is not the actual speed. There is no way of determining the wifi speed before the download starts. What you can do is that, start showing the estimated time as the download is started based on the current download speed. For this -

    1. find out how much data is downloaded in a small chunk of time like 2 sec which will be current_speed = data_downloaded/time (time can be 2 sec or anything you want)
    2. Now the estimated time will be file_size/current_speed.

    So in this way you can start showing the estimated time just 1 or 2 seconds after the download is started.