ITeye博客

多线程下载 附源码

leequer · 2010-10-18 14:58 · android · 移动开发 · Markdown

多线程下载:1.多线程2 下载 这些也是android软件多线程下载的原理 通用 思路:要多线程下载,就要知道这个文件有多大,准备用几个线程来下载。 1, 得到文件的大小:


String imgPathString = "http://dl1.g-fox.cn/chinaedition/releases/zh-CN/FirefoxChinaEdition-latest.exe";
		URL url = new URL(imgPathString);
		int size = getDateSize(imgPathString);//得到文件的大小

2,设定有3个线程 那计算每个线程下载多少


                int threadSize =3;//线程数量:3
		int block = size / threadSize +1;//每个线程下载的数据的大小

3.新建一个和要下载的文件一样大小的文件 用来保存被下载的文件


	File file = new File ("huohu.exe");
		RandomAccessFile rfile = new RandomAccessFile(file,"rw");
		rfile.setLength(size);
		rfile.close();

4.开始下载


for(int i = 0 ;i<threadSize;i++)
		{
			int startPosition = i*block;//从什么位置开始写
			
			RandomAccessFile threadfile = new RandomAccessFile(file,"rw");
			threadfile.seek(startPosition);
			new DownLoadThread(url, startPosition, threadfile, block).start();
			
		}


思路就是这样, 详细代码见源码。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。