Android多线程断点续传

最近项目要用到多线程断点续传功能,于是封装了个jar包,感觉挺方便

多线程断点续传说白了就是多条线程去下载同一资源,每条下载线程负责资源某一部分的下载任务,最终合并成一个文件,这样可以提高整体的速度;当遇到线程中断、网络中断时能够保存好各个线程已经下载到的位置,当再次去下载前一次未下载完的资源时能恢复到上次下载时的状态继续下载,这样可以省去很多流量而不用重新重头开始下载。

以下是jar包中一些主要类的介绍:

DBOpenHelper.java 负责sqlite数据库的初始化,表的创建

package com.justsy.eleschoolbag.mutildownload;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 数据库操作类
 * @author 网友
 *
 */
public class DBOpenHelper extends SQLiteOpenHelper {
	
	//数据库名
	private static final String DBNAME = "down.db";
	private static final int VERSION = 1;
	
	/**
	 * 构造器
	 * @param context
	 */
	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 LONG)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS filedownlog");
		onCreate(db);
	}
}
FileService.java  对数据库表的增删改查

package com.justsy.eleschoolbag.mutildownload;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class FileService {
	private DBOpenHelper openHelper;

	public FileService(Context context) {
		openHelper = new DBOpenHelper(context);
	}
	
	/**
	 * 获取每条线程已经下载的文件长度
	 * @param path
	 * @return
	 */
	public Map<Integer, Long> getData(String path){
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[]{path});
		Map<Integer, Long> data = new HashMap<Integer, Long>();
		
		while(cursor.moveToNext()){
			data.put(cursor.getInt(0), cursor.getLong(1));
		}
		
		cursor.close();
		db.close();
		return data;
	}
	
	/**
	 * 保存每条线程已经下载的文件长度
	 * @param path
	 * @param map
	 */
	public void save(String path,  Map<Integer, Long> map){//int threadid, int position
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		
		try{
			for(Map.Entry<Integer, Long> 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, Long> map){
		
		System.out.println("map:"+map);
		
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.beginTransaction();
		
		try{
			for(Map.Entry<Integer, Long> 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();
	}
}

FileDownloader.java  下载器,对下载进行实际管理,进行一些数据的初始化工作,启动下载

package com.justsy.eleschoolbag.mutildownload;

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 android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 下载器
 * @author Tibib
 *
 */
@SuppressLint("DefaultLocale")
public class FileDownloader {
	
	private static final String TAG = "FileDownloader";
	private Context context;
	private FileService fileService;	
	
	/* 已下载文件长度 */
	private long downloadSize = 0;
	
	/* 原始文件长度 */
	private long fileSize = 0;
	
	/* 线程数 */
	private DownloadThread[] threads;
	
	/* 本地保存文件 */
	private File saveFile;
	
	/* 缓存各线程下载的长度*/
	private Map<Integer, Long> data = new ConcurrentHashMap<Integer, Long>();
	
	/* 每条线程下载的长度 */
	private long block;
	
	/* 下载路径  */
	private String downloadUrl;
	
	/* 下载是否完成Handler */
	private Handler finishHandler;
	
	/* 文件保存路径 */
	private File fileSaveDir;
	
	/* 文件名称 */
	private String fileName;
	
	/* 开启下载的线程数 */
	private int threadNum;

	/* 下载是否暂停 */
	private boolean isRun = true;
	
	/**
	 * 构建文件下载器
	 * @param downloadUrl 下载路径
	 * @param fileSaveDir 文件保存目录
	 * @param threadNum 下载线程数
	 */
	
	public FileDownloader(Context context, Handler finishHandler,String downloadUrl, File fileSaveDir, String fileName,int threadNum) {
		
		this.context = context;
		this.finishHandler = finishHandler;
		this.downloadUrl = downloadUrl;
		this.fileSaveDir = fileSaveDir;
		this.fileName = fileName;
		this.threadNum = threadNum;
		
	}
	
	/**
	 * 开始下载
	 * @throws Exception
	 */
	public void download() throws Exception{
		
		//初始化数据
		try{
			initData();
		}catch(Exception e){
			throw e;
		}
		
		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, 0L);//初始化每条线程已经下载的数据长度为0
				}
			}
			
			for (int i = 0; i < this.threads.length; i++) {//开启线程进行下载
				long 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].start();
					//Thread.sleep(5*1000);
				}else{
					this.threads[i] = null;
				}
			}
			
			this.fileService.save(this.downloadUrl, this.data);

		} catch (Exception e) {
			print(e.toString());
			throw new Exception("file download fail");
		}
	}
	
	
	/**
	 * 下载之前进行数据的初始化工作
	 * @throws Exception
	 */
	private void initData() throws Exception{
		try {
			
			//为暂停后重新下载做准备
			this.downloadSize = 0L;
			this.isRun = true;
			
			this.fileService = new FileService(this.context);
			URL url = new URL(this.downloadUrl);
			if(!this.fileSaveDir.exists()) this.fileSaveDir.mkdirs();
			this.threads = new DownloadThread[this.threadNum];					
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(30*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 ");
				
				//没有指定文件名
				if(this.fileName!=null&&!"".equals(this.fileName)){
					this.saveFile = new File(this.fileSaveDir, this.fileName);//构建保存文件
				}else{//否则获取服务器的文件名称
					String filename = getFileName(conn);//获取文件名称
					this.saveFile = new File(this.fileSaveDir, filename);//构建保存文件
				}
				
				Map<Integer, Long> logdata = this.fileService.getData(this.downloadUrl);//获取下载记录
				
				Log.i(TAG, "数据库存在的线程下载数据:"+logdata);
				
				if(logdata.size()>0){//如果存在下载记录
					for(Map.Entry<Integer, Long> entry : logdata.entrySet())
						this.data.put(entry.getKey(), entry.getValue());//把各条线程已经下载的数据长度放入data中
				}
				
				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);
				}
				
				//计算每条线程下载的数据长度
				this.block = (this.fileSize % this.threads.length)==0? this.fileSize / this.threads.length : this.fileSize / this.threads.length + 1;
			}else{
				throw new Exception("server no response ");
			}
		} catch (Exception e) {
			print(e.toString());
			throw new Exception("don't connection this url");
		}
	}
	
	/**
	 * 获取文件名
	 * @param conn
	 * @return
	 */
	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;
	}
	
	public boolean isRun() {
		return isRun;
	}

	public void setRun(boolean isRun) {
		this.isRun = isRun;
	}

	/**
	 * 当前下载的长度
	 * @return
	 */
	public long getDownloadSize() {
		return downloadSize;
	}

	/**
	 * 获取线程数
	 */
	public int getThreadSize() {
		return threads.length;
	}
	
	/**
	 * 获取文件大小
	 * @return
	 */
	public long getFileSize() {
		return fileSize;
	}
	
	
	
	public Handler getFinishHandler() {
		return finishHandler;
	}

	
	
	public Map<Integer, Long> getData() {
		return data;
	}

	public FileService getFileService() {
		return fileService;
	}

	public void setDownloadSize(long downloadSize) {
		this.downloadSize = downloadSize;
	}

	/**
	 * 累计已下载大小
	 * @param size
	 */
	protected synchronized void append(int size) {
		
		downloadSize += size;
		if(downloadSize>=this.fileSize){//下载完成
			//清楚数据库表数据
			this.fileService.delete(this.downloadUrl);
			Message msg = new Message();
			msg.what = 0;//代表下载完成
			this.finishHandler.sendMessage(msg);
		}else{
			Message msg = new Message();
			msg.what = -1;//通知更新下载的进度
			this.finishHandler.sendMessage(msg);
		}
		

	}
	
	/**
	 * 更新指定线程最后下载的位置
	 * @param threadId 线程id
	 * @param pos 最后下载的位置
	 */
	public synchronized void update(int threadId, long pos) {
		this.data.put(threadId, pos);
		this.fileService.update(this.downloadUrl, this.data);
	}
	
	/**
	 * 获取下载的百分比
	 * @return 百分比
	 */
	public int getDownloadPercent(){
		
		return (int)(downloadSize*100/fileSize);
		
	}
	
	/**
	 * 获取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());
		}
	}

	/**
	 * 打印日志信息
	 * @param msg
	 */
	private static void print(String msg){
		Log.i(TAG, msg);
	}
}

DownloadThread.java  进行实际的下载工作,实时保存各线程下载数据和状态

package com.justsy.eleschoolbag.mutildownload;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 下载线程类
 * @author Tibib
 *
 */
public class DownloadThread extends Thread {
	
	private static final String TAG = "DownloadThread";
	private File saveFile;
	private URL downUrl;
	private long block;
	private int threadId = -1;	
	private long downLength;
	private FileDownloader downloader;
	
	/**
	 * 构造方法
	 * @param downloader 下载器
	 * @param downUrl 下载地址
	 * @param saveFile 保存路径
	 * @param block 每个线程负责下载的大小
	 * @param downLength 已经下载了多长
	 * @param threadId 线程ID
	 */
	public DownloadThread(FileDownloader downloader, URL downUrl, File saveFile, long block, long downLength, int threadId) {
		this.downUrl = downUrl;
		this.saveFile = saveFile;
		this.block = block;
		this.downloader = downloader;
		this.threadId = threadId;
		this.downLength = downLength;
	}
	
	@Override
	public void run() {
		
		RandomAccessFile threadfile = null;
		InputStream inStream = null;
		if(downLength < block){//未下载完成
			try {
				//使用Get方式下载
				HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();
				http.setConnectTimeout(30 * 1000);
				http.setRequestMethod("GET");
				http.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, */*");
				http.setRequestProperty("Accept-Language", "zh-CN");
				http.setRequestProperty("Referer", downUrl.toString()); 
				http.setRequestProperty("Charset", "UTF-8");
				
				long startPos = block * (threadId - 1) + downLength;//开始位置
				long endPos = block * threadId -1;//结束位置
				http.setRequestProperty("Range", "bytes=" + startPos + "-"+ endPos);//设置获取实体数据的范围
				http.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)");
				http.setRequestProperty("Connection", "Keep-Alive");
				
				Log.i(TAG, "code:"+http.getResponseCode());
				
				
				inStream = http.getInputStream();
				byte[] buffer = new byte[1024*512];
				int offset = 0;
				threadfile = new RandomAccessFile(this.saveFile, "rwd");
				threadfile.seek(startPos);
				
				//是否读到末尾并且下载器属于运行状态
				while (downloader.isRun()&&((offset = inStream.read(buffer)) != -1)) {
					
					Log.i(TAG, this.threadId+" offset");
					
					threadfile.write(buffer, 0, offset);
					downLength += offset;
					//记录所有下载的总长度
					downloader.append(offset);
					//实时更新(速度太慢了)
					downloader.update(this.threadId, downLength);
				}
			} catch (Exception e) { //线程下载过程中被中断
				
				Handler finishHandler = downloader.getFinishHandler();
				Message msg = new Message();
				msg.what = 1;//下载失败
				finishHandler.sendMessage(msg);
				
				//暂停下载
				downloader.setRun(false);
				
				print("Thread "+ this.threadId+ ":"+ e);
			}finally{
				
				if(inStream!=null){
					try {
						inStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					
				}
				
				if(threadfile!=null){
					try {
						threadfile.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			print("Thread " + this.threadId + " download finish");
		}
	}

	/**
	 * 打印日志信息
	 * @param msg
	 */
	private static void print(String msg){
		Log.i(TAG, msg);
	}

}

jar包下载地址(有源码),附带了一个实例,稍后上传

源码实例下载地址:

http://download.csdn.net/detail/tibib/4905964


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值