Android:如何限制下载速度 [英] Android: how to limit download speed
问题描述
我使用AndroidHttpClient
从互联网下载视频.有多种方法可以提高下载速度,但是我想知道如何使用AndroidHttpClient
或HttpURLConnection
降低下载速度?该解决方案是否有任何接口或配置?
I use AndroidHttpClient
to download videos from internet. There are ways to increase download speed, but I want to know how to slow down the download speed using AndroidHttpClient
or HttpURLConnection
? Is there any interfaces or configuration for that or some solution ?
** * ** * ** * ** * ** * * 更新 * ** * ** * ** * ** * ** * *
****************update*****************
进行了一些测试,发现正如Matthew Franglen所建议的,Thread.sleep(value)
可以作为一种解决方案.主要魔术是确定value
使线程进入睡眠状态.测试结果如下
Have done some test, found that as Matthew Franglen suggested, Thread.sleep(value)
can be a solution. The main magic is to determine the value
for thread to sleep. The test result is as below
no thread sleep
11-06 20:05:14.510: D/DownloadThread(6197): Current speed = 1793978
sleep 0.001s
11-06 20:02:28.433: D/DownloadThread(5290): Current speed = 339670
sleep 0.062
11-06 20:00:25.382: D/DownloadThread(4410): Current speed = 65036
sleep 0.125s
11-06 19:58:56.197: D/DownloadThread(3401): Current speed = 33383
sleep 0.25s
11-06 19:57:21.165: D/DownloadThread(2396): Current speed = 15877
sleep 0.5s
11-06 19:55:16.462: D/DownloadThread(1253): Current speed = 8061
sleep 1s
11-06 19:53:18.917: D/DownloadThread(31743): Current speed = 3979
测试表明,如果睡眠一秒钟,下载量将急剧下降至大约1/450!
The test shows if sleep for one second, the download drops drastically to about 1/450 !
这取决于下载循环中执行的操作种类,并取决于环境.这是特定情况下的实验结论
While this depends on what kinds operations have done in the downloading loop, and depends on the enviromnet. this is a experimental conclusion under specific case
推荐答案
降低下载速度非常简单.只是从InputStream读得更慢:
Slowing the download speed is quite simple. Just read from the InputStream more slowly:
public byte[] rateLimitedDownload(InputStream in, int bytesPerSecond) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[bytesPerSecond];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// nothing
}
}
return out.toByteArray();
}
此代码不是完美的-实际花费的所有时间都不会考虑在内,并且读取的次数可能少于预期.它应该可以给您一个想法.
This code isn't perfect - any time spent actually reading from in is not considered, and reads may be less than expected. It should give you an idea though.
这篇关于Android:如何限制下载速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!