HttpURLConnection下载限速的方法

long bytesReadBandwidth = 0L;
long lastTime = System.currentTimeMillis();

while ((bytesRead = inputStream.read(buffer)) != -1) {
    // ...

    bytesReadBandwidth += bytesRead;
    if (bytesReadBandwidth >= localRequest.BandWidthLimit) {
        // 检查下载到限制带宽的时间,这个时间小于1秒,这1秒剩下的时间就不读数据了,干耗着
        long offsetTime = System.currentTimeMillis() - lastTime;
        if (offsetTime < 1000L) {
            try {
                if (offsetTime < 0) offsetTime = 0;
                Thread.sleep(1000L - offsetTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        lastTime = System.currentTimeMillis();
        bytesReadBandwidth = 0;
    }
}

BandWidthLimit 的取值:
PS:这里 read(buffer) 的单位是byte

限制1Mbps(1/8M byte/s)的话,就填 1024x1024/8=131072
限制8Mbps(1M byte/s)的话,就填 1024x1024=1048576

你可能感兴趣的:(Android)