Android多線程斷點續傳

來源:互聯網
上載者:User

最近項目要用到多線程斷點續傳功能,於是封裝了個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);}@Overridepublic void onCreate(SQLiteDatabase db) {//建表db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, downlength LONG)");}@Overridepublic 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 positionSQLiteDatabase 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;}@Overridepublic 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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.