Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/Java: How To Stop Download After 5 Seconds?

I am using an AsyncTask to download a file, with the purpose of measuring the download speed of the connection. I want to stop the download after 5 seconds, so that I can check the total number of bytes downloaded and calculate the speed. Here's the code I am using (this is placed inside the doInBackground() method):

try{                
    InputStream is = new URL("http://www.domain.com/linux.iso").openStream();
    byte[] buf = new byte[1024];

    long startTime = System.nanoTime();
    long limitTime = System.nanoTime();
    long difference = 0;    

    while (difference < 5000000000){ /*5 billion nanoseconds = 5 seconds*/
        is.read(buf);
        limitTime = System.nanoTime();
        difference = limitTime - startTime;
    }           

    is.close();
}
catch(Exception e){
    e.printStackTrace();
} 

When connected to WiFi this is working fine. The measured speed is pretty accurate, and it takes exactly 5 seconds to complete the test. Once I move to 3G, though, the test takes from 10 up to 15 seconds to complete (I noticed that the slower the connection the longer it takes to complete).

How come? I am guessing that the OS is waiting for the replies of the read() requests it sent, but not sure.

Do you know a way that will cap the download at 5 seconds no matter what?

Thanks in advance.

like image 563
Daniel Scocco Avatar asked Sep 01 '26 11:09

Daniel Scocco


2 Answers

You need to separate time calculation and download in different threads. You are right, since both are in the same thread, limitTime = System.nanoTime(); will only get executed when is.read(buf); is completed

like image 62
Mohamed_AbdAllah Avatar answered Sep 03 '26 00:09

Mohamed_AbdAllah


read() is definitely a blocking call. But I think this is a result of having to wait for the cell radio in the phone to power up to full power.

One way to tell for sure would be to open a browser, surf to a page, then after the page is loaded, do your test.

There was a very interesting Google IO talk this year about how the cell radio sits in an idle/low-power state most of the time, and takes a few seconds to "warm up"

I'll see if I can find the link to the video.

Edit: here's the video:

http://www.youtube.com/watch?v=PwC1OlJo5VM

Battery talk starts about 17:12

http://www.youtube.com/watch?v=PwC1OlJo5VM&feature=player_detailpage#t=1032s

Ramp-up is ~2 seconds it looks like.

A slide from the presentation:

enter image description here

like image 33
pjco Avatar answered Sep 03 '26 01:09

pjco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!