문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top