Android: how to limit download speed

跟風遠走 提交于 2019-12-24 13:43:07

问题


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*****************

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/19808396/android-how-to-limit-download-speed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!