mercredi 22 juin 2016

Android calculate download speed test

I am trying to calculate a download speed test calculate. Found a lot info in Stackoverflow but nothing help me. The final calculation is not logic. Attached my code that I found.

 public void run() {
            OutputStream out = null;
            URLConnection conn = null;
            InputStream in = null;
            try
            {
                URL url1 = new URL("test");
                out = new BufferedOutputStream(new FileOutputStream(getVideoFile().getPath()));
                conn = url1.openConnection();
                in = conn.getInputStream();
                long start = System.currentTimeMillis();
                byte[] buffer = new byte[1024];
                int numRead;
                long numWritten = 0;
                while ((numRead = in.read(buffer)) != -1)
                {
                    out.write(buffer, 0, numRead);
                    numWritten += numRead;

                    long end = System.currentTimeMillis();

                    if ((end - start)>0) {
                        double rate = 1000f *  numWritten / (end - start) ;
                        Log.d("downloadmanager","speed "+rate);
                    }
                }

                rate = Math.round( rate * 100.0 ) / 100.0;
                String ratevalue;
                if(rate > 1000)
                    ratevalue = String.valueOf(rate / 1024).concat(" Mbps");
                else
                    ratevalue = String.valueOf(rate).concat(" Kbps");
                Log.d("DownloadManager", "download speed: " + ratevalue);*/

            }
            catch (Exception ex)
            {
                Log.d("downloadmanager","Unknown Error: " + ex);
            }
            finally
            {
                try
                {
                    if (in != null)
                    {
                        in.close();
                    }
                    if (out != null)
                    {
                        out.close();
                    }
                }
                catch (IOException ex)
                {
                    Log.d("downloadmanager", "Unknown Error: " + ex);
                }
            }
        }
    }).start();

Thanks for helping figure this up.

Aucun commentaire:

Enregistrer un commentaire