基于Android的HTTP下载速度提升

Android

只为极速下载

因素

HTTP下载速度受限于两个因素,这里不讨论服务器限制以及多线程

  • 带宽网速
  • 文件写入速度

速度提升

由于带宽是固定的,因此,文件读写速度是下载速度的关键。

BufferedRandomAccessFile

普遍的,我们使用RandomAccessFile进行断点下载,对文件读写操作,线程对磁盘的读写非常频繁,导致写入文件非常慢,从而导致下载速度慢。因此,采用具有缓冲的RandomAccessFile,能快速降低磁盘的IO。

以下是测试速度对比,转载自https://blog.csdn.net/hpb21/article/details/51270873

耗时(s)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935
BufferedRandomAccessFile BufferedRandomAccessFile 0.401

块传输

通过对比,FileChannel写文件速度优于普通的复制文件方法

写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 使用块传输,直接通过追加的形式,写入到文件里
*
* @param inputStream
*/
private void dynamicTransmission(InputStream inputStream) throws Exception
{
FileOutputStream outputStream = new FileOutputStream(mTempFile, true);
FileChannel channel = outputStream.getChannel();
ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
ByteBuffer buffer = ByteBuffer.allocate(STREAM_LEN);
int read;
while ((read = readableByteChannel.read(buffer)) != -1)
{
buffer.flip();
channel.write(buffer);
buffer.compact();

mTaskEntity.downloadLen += read;
onProgressChange(mTaskEntity.fileSize, mTaskEntity.downloadLen);

if (mTaskEntity.isCancel)
{
onCancel();
break;
}
}
outputStream.close();
channel.close();
readableByteChannel.close();
}

示例

Downloader,欢迎star!

使用上述两种方式,下载速度明显提高了。

谢谢老板,请尽情用红包来蹂躏我吧!!!
0%