现在的位置: 首页 > 综合 > 正文

Android 下使用 Http 协议实现多线程断点续传下载

2014年01月20日 ⁄ 综合 ⁄ 共 4619字 ⁄ 字号 评论关闭

0.使用多线程下载会提升文件下载的速度,那么多线程下载文件的过程是:

(1)首先获得下载文件的长度,然后设置本地文件的长度

HttpURLConnection.getContentLength();

RandomAccessFile file = new RandomAccessFile("QQWubiSetup.exe","rwd");

file.setLength(filesize);//设置本地文件的长度

(2)根据文件长度和线程数计算每条线程下载的数据长度和下载位置。

如:文件的长度为6M,线程数为3,那么,每条线程下载的数据长度为2M,每条线程开始下载的位置如下图所示。



例如10M大小,使用3个线程来下载,

线程下载的数据长度 (10%3 == 0 ? 10/3:10/3+1) ,第1,2个线程下载长度是4M,第三个线程下载长度为2M

下载开始位置:线程id*每条线程下载的数据长度 = ?

下载结束位置:(线程id+1)*每条线程下载的数据长度-1=?

(3)使用Http的Range头字段指定每条线程从文件的什么位置开始下载,下载到什么位置为止,

如:指定从文件的2M位置开始下载,下载到位置(4M-1byte)为止

代码如下:HttpURLConnection.setRequestProperty("Range", "bytes=2097152-4194303");

(4)保存文件,使用RandomAccessFile类指定每条线程从本地文件的什么位置开始写入数据。

RandomAccessFile threadfile = new RandomAccessFile("QQWubiSetup.exe ","rwd");

threadfile.seek(2097152);//从文件的什么位置开始写入数据

1.多线程下载的核心代码示例

view plaincopy to clipboardprint?
public class MulThreadDownload
{
/**
* 多线程下载
* @param args
*/
public static void main(String[] args)
{
String path = "http://net.hoo.com/QQWubiSetup.exe";
try
{
new MulThreadDownload().download(path, 3);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 从路径中获取文件名称
* @param path 下载路径
* @return
*/
public static String getFilename(String path)
{
return path.substring(path.lastIndexOf('/')+1);
}
/**
* 下载文件
* @param path 下载路径
* @param threadsize 线程数
*/
public void download(String path, int threadsize) throws Exception
{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
//获取要下载的文件的长度
int filelength = conn.getContentLength();
//从路径中获取文件名称
String filename = getFilename(path);
File saveFile = new File(filename);
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
//设置本地文件的长度和下载文件相同
accessFile.setLength(filelength);
accessFile.close();
//计算每条线程下载的数据长度
int block = filelength%threadsize==0? filelength/threadsize : filelength/threadsize+1;
for(int threadid=0 ; threadid < threadsize ; threadid++){
new DownloadThread(url, saveFile, block, threadid).start();
}
}

private final class DownloadThread extends Thread
{
private URL url;
private File saveFile;
private int block;//每条线程下载的数据长度
private int threadid;//线程id
public DownloadThread(URL url, File saveFile, int block, int threadid)
{
this.url = url;
this.saveFile = saveFile;
this.block = block;
this.threadid = threadid;
}
@Override
public void run()
{
//计算开始位置公式:线程id*每条线程下载的数据长度= ?
//计算结束位置公式:(线程id +1)*每条线程下载的数据长度-1 =?
int startposition = threadid * block;
int endposition = (threadid + 1 ) * block - 1;
try
{
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
//设置从什么位置开始写入数据
accessFile.seek(startposition);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
conn.setRequestProperty("Range", "bytes="+ startposition+ "-"+ endposition);
InputStream inStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 )
{
accessFile.write(buffer, 0, len);
}
inStream.close();
accessFile.close();
System.out.println("线程id:"+ threadid+ "下载完成");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

2.多线程断点下载功能,这里把断点数据保存到数据库中:注意代码注释的理解

(0)主Activity,关键点使用Handler更新进度条与开启线程下载避免ANR

若不使用Handler却要立即更新进度条数据,可使用:

//resultView.invalidate(); UI线程中立即更新进度条方法

//resultView.postInvalidate(); 非UI线程中立即更新进度条方法

view plaincopy to clipboardprint?
/**
* 注意这里的设计思路,UI线程与参数保存问题,避免ANR问题,UI控件的显示
* @author kay
*
*/
public class DownloadActivity extends Activity
{
private EditText downloadpathText;
private TextView resultView;
private ProgressBar progressBar;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

downloadpathText = (EditText) this.findViewById(R.id.downloadpath);
progressBar = (ProgressBar) this.findViewById(R.id.downloadbar);
resultView = (TextView) this.findViewById(R.id.result);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//取得下载路径
String path = downloadpathText.getText().toString();
//判断SDCard是否存在
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
//下载操作
download(path, Environment.getExternalStorageDirectory());
}
else
{
Toast.makeText(DownloadActivity.this, R.string.sdcarderror, 1).show();
}
}
});
}
//主线程(UI线程)
//业务逻辑正确,但是该程序运行的时候有问题(可能出现ANR问题)
//对于显示控件的界面更新只是由UI线程负责,如果是在非UI线程更新控件的属性值,更新后的显示界面不会反映到屏幕上
/**
* 参数类型:因为启动一个线程还需要使用到上面方法的参数,而主方法启动后很快就会销毁,
* 那么使用Final可以解决参数丢失的问题
* path 注意是Final类型
* savedir 注意是Final类型
*/
private void download(final String path, final File savedir)
{
//这里开启一个线程避免ANR错误
new Thread(new Runnable()
{
@Override
public void run()
{
FileDownloader loader = new FileDownloader(DownloadActivity.this, path, savedir, 3);
//设置进度条的最大刻度为文件的长度
progressBar.setMax(loader.getFileSize());
try
{
loader.download(new DownloadProgressListener()
{
/**
* 注意这里的设计,显示进度条数据需要使用Handler来处理
* 因为非UI线程更新后的数据不能被刷新
*/
@Override
public void onDownloadSize(int size)
{
//实时获知文件已经下载的数据长度
Message msg = new Message();

抱歉!评论已关闭.