的Andr​​oid / Java的:如何阻止下载5秒后? [英] Android/Java: How To Stop Download After 5 Seconds?

查看:182
本文介绍了的Andr​​oid / Java的:如何阻止下载5秒后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是AsyncTask的下载文件中,测量连接的下载速度的目的。我想在5秒后停止下载,这样我可以检查下载的字节总数和计算速度。这里的code我使用(这被放置在doInBackground()方法中):

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();
} 

当连接到无线网络这个是工作的罚款。测得的速度是pretty准确,到底需要5秒完成测试。有一次,我向3G网络,不过,测试从10达15秒至完成(我注意到,速度较慢的连接时间越长才能完成)。

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.

你知道的方式,将在5秒帽下载不管是什么?

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

先谢谢了。

推荐答案

阅读()绝对是一个阻塞调用。但我认为这是具有等待小区无线在手机上电到全功率的结果。

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.

有一个非常有趣的谷歌IO谈谈小区无线电如何坐在空闲/低功耗状态的大部分时间,并需要几秒钟的热身,今年

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.

编辑:这里的视频:

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

电池通话时间约开始17:12

Battery talk starts about 17:12

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

斜坡上升为约2秒样子。

Ramp-up is ~2 seconds it looks like.

从presentation幻灯片:

A slide from the presentation:

这篇关于的Andr​​oid / Java的:如何阻止下载5秒后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆