您的位置:首页 > 移动开发 > Android开发

android多线程下载以及断点续传

2014-09-08 15:40 239 查看
转载自

使用多线程下载文件可以更快完成文件的下载,多线程下载文件之所以快,是因为其抢占的服务器资源多。如:假设服务器同时最多服务100个用户,在服务器中一条线程对应一个用户,100条线程在计算机中并非并发执行,而是由CPU划分时间片轮流执行,如果A应用使用了99条线程下载文件,那么相当于占用了99个用户的资源,假设一秒内CPU分配给每条线程的平均执行时间是10ms,A应用在服务器中一秒内就得到了990ms的执行时间,而其他应用在一秒内只有10ms的执行时间。就如同一个水龙头,每秒出水量相等的情况下,放990毫秒的水

肯定比放10毫秒的水要多。

多线程下载的实现过程:

1>首先得到下载文件的长度,然后设置本地文件

的长度。

HttpURLConnection.getContentLength();

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

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

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

3>使用Http的Range头字段指定每条线程从文件的什么位置开始下载,下载到什么位置为止,如:指定从文件的2M位置开始下载,下载到位置(4M-1byte)为止,代码如下:

HttpURLConnection.setRequestProperty("Range", "bytes=2097152-4194303");

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

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

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

MulTreadDownload.java

[java] view
plaincopy

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.RandomAccessFile;

import java.net.HttpURLConnection;

import java.net.URL;

public class MulThreadDownloadTest {

public static void main(String[] args) throws Exception{

new MulThreadDownloadTest().downlaod();

}

public void downlaod() throws Exception{

String path = "http://net.itcast.cn/QQWubiSetup.exe";

//文件的长度

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(5*1000);

int length = conn.getContentLength();//得到文件的长度

int threadnum = 5;

int block = length%threadnum==0 ? length/threadnum : length/threadnum+1;//计算每条线程下载的数据长度

File file = new File("QQWubiSetup.exe");

RandomAccessFile rfile = new RandomAccessFile(file, "rwd");

rfile.setLength(length);//把本地文件的长度设置为网络文件的长度

rfile.close();

for(int i=0 ; i < threadnum ; i++){

new DownloadThread(block, url, file ,i).start();

}

}

private final class DownloadThread extends Thread{

private int block;//每条线程下载的数据长度

private URL url;//下载路径

private File file;//本地文件

private int threaid;//线程id

public DownloadThread(int block, URL url, File file, int i) {

this.block = block;

this.url = url;

this.file = file;

this.threaid = i;

}

@Override

public void run() {

try {

int startpos = threaid * block;//计算该线程从文件的什么位置开始下载

int endpos = (threaid+1) * block - 1;//计算该线程下载到文件的什么位置结束

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(5*1000);

conn.setRequestProperty("Range", "bytes="+ startpos+"-"+ endpos);

InputStream inputStream = conn.getInputStream();

RandomAccessFile rfile = new RandomAccessFile(file, "rwd");

rfile.seek(startpos);

byte[] buffer = new byte[1024];

int len = 0;

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

rfile.write(buffer, 0, len);

}

rfile.close();

inputStream.close();

System.out.println("线程"+ (threaid+1)+ "下载完成");

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

实现断点续传

有两种方式可以保存断点数据:

1.通过文件的形式保存

2 通过数据库的方式保存,如果需要查询的话则要此种方式,即使用Sqllite保存

下面看看如何数据库保存

建立表结构

DBOpenHelper.java

[java] view
plaincopy

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper {

private static final String DBNAME = "itcast.db";

private static final int VERSION = 1;

public DBOpenHelper(Context context) {

super(context, DBNAME, null, VERSION);

}

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, downlength INTEGER)");

}

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS filedownlog");

onCreate(db);

}

}

如何操作表,实现对断点数据的一个操作

FileService.java

[java] view
plaincopy

import java.util.HashMap;

import java.util.Map;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

/**

* 业务bean

*

*/

public class FileService {

private DBOpenHelper openHelper;

public FileService(Context context) {

openHelper = new DBOpenHelper(context);

}

/**

* 获取每条线程已经下载的文件长度

* @param path

* @return

*/

public Map<Integer, Integer> getData(String path){

SQLiteDatabase db = openHelper.getReadableDatabase();

Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[]{path});

Map<Integer, Integer> data = new HashMap<Integer, Integer>();

while(cursor.moveToNext()){

data.put(cursor.getInt(0), cursor.getInt(1));

}

cursor.close();

db.close();

return data;

}

/**

* 保存每条线程已经下载的文件长度

* @param path

* @param map

*/

public void save(String path, Map<Integer, Integer> map){//int threadid, int position

SQLiteDatabase db = openHelper.getWritableDatabase();

db.beginTransaction();

try{

for(Map.Entry<Integer, Integer> entry : map.entrySet()){

db.execSQL("insert into filedownlog(downpath, threadid, downlength) values(?,?,?)",

new Object[]{path, entry.getKey(), entry.getValue()});

}

db.setTransactionSuccessful();

}finally{

db.endTransaction();

}

db.close();

}

/**

* 实时更新每条线程已经下载的文件长度

* @param path

* @param map

*/

public void update(String path, Map<Integer, Integer> map){

SQLiteDatabase db = openHelper.getWritableDatabase();

db.beginTransaction();

try{

for(Map.Entry<Integer, Integer> entry : map.entrySet()){

db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?",

new Object[]{entry.getValue(), path, entry.getKey()});

}

db.setTransactionSuccessful();

}finally{

db.endTransaction();

}

db.close();

}

/**

* 当文件下载完成后,删除对应的下载记录

* @param path

*/

public void delete(String path){

SQLiteDatabase db = openHelper.getWritableDatabase();

db.execSQL("delete from filedownlog where downpath=?", new Object[]{path});

db.close();

}

}

实现断点数据的保存

FileDownload.java

[java] view
plaincopy

import java.io.File;

import java.io.RandomAccessFile;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.UUID;

import java.util.concurrent.ConcurrentHashMap;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import cn.itcast.service.FileService;

import android.content.Context;

import android.util.Log;

/**

* 文件下载器

* @author lihuoming@sohu.com

*/

public class FileDownloader {

private static final String TAG = "FileDownloader";

private Context context;

private FileService fileService;

/* 已下载文件长度 */

private int downloadSize = 0;

/* 原始文件长度 */

private int fileSize = 0;

/* 线程数 */

private DownloadThread[] threads;

/* 本地保存文件 */

private File saveFile;

/* 缓存各线程下载的长度*/

private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();

/* 每条线程下载的长度 */

private int block;

/* 下载路径 */

private String downloadUrl;

/**

* 获取线程数

*/

public int getThreadSize() {

return threads.length;

}

/**

* 获取文件大小

* @return

*/

public int getFileSize() {

return fileSize;

}

/**

* 累计已下载大小

* @param size

*/

protected synchronized void append(int size) {

downloadSize += size;

}

/**

* 更新指定线程最后下载的位置

* @param threadId 线程id

* @param pos 最后下载的位置

*/

protected void update(int threadId, int pos) {

this.data.put(threadId, pos);

}

/**

* 保存记录文件

*/

protected synchronized void saveLogFile() {

this.fileService.update(this.downloadUrl, this.data);

}

/**

* 构建文件下载器

* @param downloadUrl 下载路径

* @param fileSaveDir 文件保存目录

* @param threadNum 下载线程数

*/

public FileDownloader(Context context, String downloadUrl, File fileSaveDir, int threadNum) {

try {

this.context = context;

this.downloadUrl = downloadUrl;

fileService = new FileService(this.context);

URL url = new URL(this.downloadUrl);

if(!fileSaveDir.exists()) fileSaveDir.mkdirs();

this.threads = new DownloadThread[threadNum];

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5*1000);

conn.setRequestMethod("GET");

conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");

conn.setRequestProperty("Accept-Language", "zh-CN");

conn.setRequestProperty("Referer", downloadUrl);

conn.setRequestProperty("Charset", "UTF-8");

conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.connect();

printResponseHeader(conn);

if (conn.getResponseCode()==200) {

this.fileSize = conn.getContentLength();//根据响应获取文件大小

if (this.fileSize <= 0) throw new RuntimeException("Unkown file size ");

String filename = getFileName(conn);

this.saveFile = new File(fileSaveDir, filename);/* 保存文件 */

Map<Integer, Integer> logdata = fileService.getData(downloadUrl);

if(logdata.size()>0){

for(Map.Entry<Integer, Integer> entry : logdata.entrySet())

data.put(entry.getKey(), entry.getValue());

}

this.block = (this.fileSize % this.threads.length)==0? this.fileSize / this.threads.length : this.fileSize / this.threads.length + 1;

if(this.data.size()==this.threads.length){

for (int i = 0; i < this.threads.length; i++) {

this.downloadSize += this.data.get(i+1);

}

print("已经下载的长度"+ this.downloadSize);

}

}else{

throw new RuntimeException("server no response ");

}

} catch (Exception e) {

print(e.toString());

throw new RuntimeException("don't connection this url");

}

}

/**

* 获取文件名

*/

private String getFileName(HttpURLConnection conn) {

String filename = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);

if(filename==null || "".equals(filename.trim())){//如果获取不到文件名称

for (int i = 0;; i++) {

String mine = conn.getHeaderField(i);

if (mine == null) break;

if("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())){

Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());

if(m.find()) return m.group(1);

}

}

filename = UUID.randomUUID()+ ".tmp";//默认取一个文件名

}

return filename;

}

/**

* 开始下载文件

* @param listener 监听下载数量的变化,如果不需要了解实时下载的数量,可以设置为null

* @return 已下载文件大小

* @throws Exception

*/

public int download(DownloadProgressListener listener) throws Exception{

try {

RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");

if(this.fileSize>0) randOut.setLength(this.fileSize);

randOut.close();

URL url = new URL(this.downloadUrl);

if(this.data.size() != this.threads.length){

this.data.clear();

for (int i = 0; i < this.threads.length; i++) {

this.data.put(i+1, 0);

}

}

for (int i = 0; i < this.threads.length; i++) {

int downLength = this.data.get(i+1);

if(downLength < this.block && this.downloadSize<this.fileSize){ //该线程未完成下载时,继续下载

this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);

this.threads[i].setPriority(7);

this.threads[i].start();

}else{

this.threads[i] = null;

}

}

this.fileService.save(this.downloadUrl, this.data);

boolean notFinish = true;//下载未完成

while (notFinish) {// 循环判断是否下载完毕

Thread.sleep(900);

notFinish = false;//假定下载完成

for (int i = 0; i < this.threads.length; i++){

if (this.threads[i] != null && !this.threads[i].isFinish()) {

notFinish = true;//下载没有完成

if(this.threads[i].getDownLength() == -1){//如果下载失败,再重新下载

this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);

this.threads[i].setPriority(7);

this.threads[i].start();

}

}

}

if(listener!=null) listener.onDownloadSize(this.downloadSize);

}

fileService.delete(this.downloadUrl);

} catch (Exception e) {

print(e.toString());

throw new Exception("file download fail");

}

return this.downloadSize;

}

/**

* 获取Http响应头字段

* @param http

* @return

*/

public static Map<String, String> getHttpResponseHeader(HttpURLConnection http) {

Map<String, String> header = new LinkedHashMap<String, String>();

for (int i = 0;; i++) {

String mine = http.getHeaderField(i);

if (mine == null) break;

header.put(http.getHeaderFieldKey(i), mine);

}

return header;

}

/**

* 打印Http头字段

* @param http

*/

public static void printResponseHeader(HttpURLConnection http){

Map<String, String> header = getHttpResponseHeader(http);

for(Map.Entry<String, String> entry : header.entrySet()){

String key = entry.getKey()!=null ? entry.getKey()+ ":" : "";

print(key+ entry.getValue());

}

}

private static void print(String msg){

Log.i(TAG, msg);

}

public static void main(String[] args) {

/* FileDownloader loader = new FileDownloader(context, "http://browse.babasport.com/ejb3/ActivePort.exe",

new File("D:\\androidsoft\\test"), 2);

loader.getFileSize();//得到文件总大小

try {

loader.download(new DownloadProgressListener(){

public void onDownloadSize(int size) {

print("已经下载:"+ size);

}

});

} catch (Exception e) {

e.printStackTrace();

}*/

}

}

DownloadActivity.java

[java] view
plaincopy

package cn.itcast.download;

import java.io.File;

import cn.itcast.net.download.DownloadProgressListener;

import cn.itcast.net.download.FileDownloader;

import android.app.Activity;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ProgressBar;

import android.widget.TextView;

import android.widget.Toast;

public class DownloadActivity extends Activity {

private ProgressBar downloadbar;

private EditText pathText;

private TextView resultView;

private Handler handler = new Handler(){

@Override

public void handleMessage(Message msg) {

switch (msg.what) {

case 1:

int size = msg.getData().getInt("size");

downloadbar.setProgress(size);

float result = (float)downloadbar.getProgress()/ (float)downloadbar.getMax();

int p = (int)(result*100);

resultView.setText(p+"%");

if(downloadbar.getProgress()==downloadbar.getMax())

Toast.makeText(DownloadActivity.this, R.string.success, 1).show();

break;

case -1:

Toast.makeText(DownloadActivity.this, R.string.error, 1).show();

break;

}

}

};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Button button = (Button)this.findViewById(R.id.button);

downloadbar = (ProgressBar)this.findViewById(R.id.downloadbar);

pathText = (EditText)this.findViewById(R.id.path);

resultView = (TextView)this.findViewById(R.id.result);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String path = pathText.getText().toString();

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

File dir = Environment.getExternalStorageDirectory();//文件保存目录

download(path, dir);

}else{

Toast.makeText(DownloadActivity.this, R.string.sdcarderror, 1).show();

}

}

});

}

//对于UI控件的更新只能由主线程(UI线程)负责,如果在非UI线程更新UI控件,更新的结果不会反映在屏幕上,某些控件还会出错

private void download(final String path, final File dir){

new Thread(new Runnable() {

@Override

public void run() {

try {

FileDownloader loader = new FileDownloader(DownloadActivity.this, path, dir, 3);

int length = loader.getFileSize();//获取文件的长度

downloadbar.setMax(length);

loader.download(new DownloadProgressListener(){

@Override

public void onDownloadSize(int size) {//可以实时得到文件下载的长度

Message msg = new Message();

msg.what = 1;

msg.getData().putInt("size", size);

handler.sendMessage(msg);

}});

} catch (Exception e) {

Message msg = new Message();

msg.what = -1;

msg.getData().putString("error", "下载失败");

handler.sendMessage(msg);

}

}

}).start();

}

}

注意://对于UI控件的更新只能由主线程(UI线程)负责,如果在非UI线程更新UI控件,更新的结果不会反映在屏幕上,某些控件还会出错

可以是通过消息队列的方式传递数据到主线程,实现进度更新
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: