標籤:android開發 多線程 資料庫 網路
前言: 項目都快交付階段了,客戶說要改個需求,添加一個斷點續傳功能。在版本更新,雜誌下載或者視頻下載的時候實現斷點續傳。由於時間緊迫,想起了之前研究過一個demo代碼,就直接修改使用了,根據自己的方式實現,但是核心代碼沒變。以後或許會用到,於是就專門寫了個demo。
先看一下項目目錄結構:
- db--->操作資料庫的(建立資料庫表,資料的增刪改查。)
- util--->工具類
- download--->實現下載(下載器以及自訂線程。)
這裡以易信用戶端的下載為例,簡要介紹。
String downloadPath = "http://gdown.baidu.com/data/wisegame/653346a13ab69081/yixin_146.apk";String fileName = "易信.apk";
在這裡我添加了通知欄,查看進度。
大致思路:根據需要下載檔案的總大小,可以自訂幾個線程同時下載動作(在這裡我給下載器構造方法重載了,預設不設定線程數量的話預設是3個)。
內部使用map鍵值對的方式緩衝線程下載資料,key是線程id,value:是下載量。同時還有個線程數組,這個線程數組和前面的Map是對應的。
在下載器中,有個迴圈會不斷檢查每個線程的下載任務是否完成,完成了則將其T掉,這樣到最後就都完成後,退出迴圈,整個下載任務就完成。刪除資料庫表中的下載記錄。
然後每個線程分配下載檔案大小值,執行下載。下載過程中,通過回調介面,回調到MainActivity畫面中,利用handler實現更新UI。
......
這裡具體的問題細節,啊還有很多,大致思路就是這樣了。
代碼裡面我都寫了詳細的注釋,貼點代碼把。希望你也能看懂。
package com.example.download;import java.io.File;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;import com.example.util.Common;import android.util.Log;/** * 用於下載檔案的線程。 該線程有被分配的工作量:block * */public class DownloadThread extends Thread {private static final String TAG = "DownloadThread";/** * 目標檔案 */private File saveFile;/** * 檔案下載路徑 */private URL downUrl;/** * 當前線程需要下載的檔案大小 */private int block;/** * 線程身份識別id */private int threadId = -1;/** * 之前已經下載的位置 */private int downLength;/** * 判斷當前線程是否結束 */private boolean isFinished = false;/** * 檔案下載器 */private FileDownloader downloader;/** * @param downloader * 下載器 * @param downUrl * 下載的網路路徑 * @param saveFile * 儲存的目標檔案 * @param block * 下載任務量 * @param downLength * 已經下載的大小 * @param threadId * 線程id */public DownloadThread(FileDownloader downloader, URL downUrl,File saveFile, int block, int downLength, int threadId) {this.downUrl = downUrl;this.saveFile = saveFile;this.block = block;this.downloader = downloader;this.threadId = threadId;this.downLength = downLength;}@Overridepublic void run() {if (downLength < block) {// 未下載完成try {// 使用Get方式下載HttpURLConnection http = Common.getHttpParams(downUrl);// 開始下載位置int startPosition = block * (threadId - 1) + downLength;// 結束下載位置int endPosition = block * threadId - 1;// 設定擷取實體資料的範圍http.setRequestProperty("Range", "bytes=" + startPosition + "-"+ endPosition);// 擷取檔案輸入資料流InputStream inStream = http.getInputStream();byte[] buffer = new byte[1024];int offset = 0;print("Thread " + this.threadId+ " start download from position " + endPosition);RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");threadfile.seek(endPosition);while ((offset = inStream.read(buffer, 0, 1024)) != -1) {threadfile.write(buffer, 0, offset);// 下載量累加downLength += offset;// 更新下載資料庫downloader.update(this.threadId, downLength);downloader.append(offset);}threadfile.close();inStream.close();print("Thread " + this.threadId + " download finish");// 設定下載完成標誌位。this.isFinished = true;} catch (Exception e) {this.downLength = -1;print("Thread " + this.threadId + ":" + e);}}}/** * 列印日誌資訊 * * @param msg */private static void print(String msg) {Log.i(TAG, msg);}/** * 下載是否完成 * * @return */public boolean isFinish() {return isFinished;}/** * 已經下載的內容大小 * * @return 如果傳回值為-1,代表下載失敗 */public long getDownLength() {return downLength;}}
下載器:
package com.example.download;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;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.content.Context;import android.util.Log;import com.example.db.DBTools;import com.example.util.Common;/** * * 檔案下載 * * * */public class FileDownloader {private static final String TAG = "FileDownloader";private Context context;/** * 操作資料庫的類 */private DBTools dbTools;/** * 已下載檔案長度 */private int downloadSize = 0;/** * 原始檔案長度 */private int fileSize = 0;/** * 線程數 */private DownloadThread[] threadArr;/** * 本地儲存檔案 */private File saveFile;/** * 預設下載線程數量 */private static final int defaultThreadSize = 3;/** * 預設檔案下載存放位置 */private static String defaultDestPath = "";/** * 用於緩衝各個線程下載的長度 * <p> * Key:對應線程id;Value:對應線程已經下載的長度 * </p> */private Map<Integer, Integer> cacheDownMap = new ConcurrentHashMap<Integer, Integer>();/** * 每條線程應該下載的長度 */private int block;/** * 檔案下載路徑 */private String downloadUrl;/** * 擷取線程數 */public int getThreadSize() {return threadArr.length;}/** * 擷取檔案大小 * * @return 需要下載檔案的總長度 */public int getFileSize() {return fileSize;}/** * 累加檔案已下載的大小 * * @param size * 此刻下載量 */protected synchronized void append(int size) {downloadSize += size;}/** * 更新指定線程最後下載的位置 * * @param threadId * 線程id * @param pos * 最後下載的位置 */protected synchronized void update(int threadId, int pos) {this.cacheDownMap.put(threadId, pos);this.dbTools.update(this.downloadUrl, this.cacheDownMap);}/** * 構建檔案下載器 * * @param downloadUrl * 下載路徑 * @param fileSaveDir * 檔案儲存目錄 * @param threadNum * 下載線程數 */public FileDownloader(Context context, String downloadUrl, String destPath,int threadNum) {this.context = context;this.downloadUrl = downloadUrl;dbTools = new DBTools(this.context);checkPath(destPath);this.threadArr = new DownloadThread[threadNum];setRequest(downloadUrl, destPath);}/** * 檢查下載路徑是否存在,不存在則建立。。 * @param destPath * @return 是否存在該目錄 */public boolean checkPath(String destPath) {File file = new File(destPath);if (!file.exists()) {boolean bol = file.mkdirs();return bol;}return true;}/** * @param context * @param downloadUrl */public FileDownloader(Context context, String downloadUrl) {this.context = context;this.downloadUrl = downloadUrl;this.threadArr = new DownloadThread[defaultThreadSize];this.dbTools = new DBTools(this.context);dbTools = new DBTools(this.context);checkPath(defaultDestPath);this.threadArr = new DownloadThread[defaultThreadSize];setRequest(downloadUrl, defaultDestPath);}/** * 封裝請求 */public void setRequest(String downUrl, String destPath) {URL url = null;try {url = new URL(downUrl);HttpURLConnection conn = Common.getHttpParams(url);conn.connect();// 列印頭部資訊printResponseHeader(conn);// 200==》成功串連...if (conn.getResponseCode() == 200) {// 擷取檔案總大小this.fileSize = conn.getContentLength();if (this.fileSize <= 0)throw new RuntimeException("該檔案很可能不存在...");// 擷取當前需要下載檔案名稱String filename = getFileName(conn);// 目標儲存檔案this.saveFile = new File(destPath, filename);// 擷取當前路徑下載記錄包括已經下載數量。Map<Integer, Integer> logdata = dbTools.getData(downUrl);// 如果存在下載記錄把各條線程已經下載的資料長度放入緩衝變數中if (logdata.size() > 0) {for (Map.Entry<Integer, Integer> entry : logdata.entrySet())cacheDownMap.put(entry.getKey(), entry.getValue());}// 下面計算所有線程已經下載的資料長度if (this.cacheDownMap.size() == this.threadArr.length) {for (int i = 0; i < this.threadArr.length; i++) {this.downloadSize += this.cacheDownMap.get(i + 1);}print("已經下載資料的長度" + this.downloadSize);}// 計算分配給每條線程下載的資料長度this.block = (this.fileSize % this.threadArr.length) == 0 ? this.fileSize/ this.threadArr.length: this.fileSize / this.threadArr.length + 1;} else {throw new RuntimeException("無響應......");}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/** * 擷取檔案名稱 * * @param conn * 本次http串連 * @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 match = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());if (match.find())return match.group(1);}}// 預設filename = UUID.randomUUID() + ".tmp";// 預設取一個檔案名稱}return filename;}/** * 開始下載檔案 * * @param listener * 監聽下載數量的變化,如果不需要瞭解即時下載的數量,可以設定為null * @return 已下載檔案大小 * @throws Exception */public int startDownload(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.cacheDownMap.size() != this.threadArr.length) {this.cacheDownMap.clear();for (int i = 0; i < this.threadArr.length; i++) {this.cacheDownMap.put(i + 1, 0);// 初始化每條線程已經下載的資料長度為0}}// 開啟線程進行下載for (int i = 0; i < this.threadArr.length; i++) {int downLength = this.cacheDownMap.get(i + 1);// 這裡的第一個條件是判斷當前該線程還沒有下載完分配數量;第二個是判斷當前總的下載量要小於需要下載的檔案總大小。if (downLength < this.block&& this.downloadSize < this.fileSize) {this.threadArr[i] = new DownloadThread(this, url,this.saveFile, this.block,this.cacheDownMap.get(i + 1), i + 1);// 提高優先順序this.threadArr[i].setPriority(7);this.threadArr[i].start();} else {// 該線程已經完任務,T掉。this.threadArr[i] = null;}}// 將下載資料插入資料庫this.dbTools.save(this.downloadUrl, this.cacheDownMap);boolean notFinish = true;// 下載未完成// 在檔案被完全下載完之前是個死迴圈,判斷所有線程是否完成下載//如果for迴圈結束了,外層while迴圈也就結束。while (notFinish) {Thread.sleep(900);notFinish = false;// 假定全部線程下載完成for (int i = 0; i < this.threadArr.length; i++) {if (this.threadArr[i] != null&& !this.threadArr[i].isFinish()) {// 如果發現線程未完成下載notFinish = true;// 設定標誌為下載沒有完成// 擷取當前線程完成任務量,如果為-1則重新下載。if (this.threadArr[i].getDownLength() == -1) {this.threadArr[i] = new DownloadThread(this, url,this.saveFile, this.block,this.cacheDownMap.get(i + 1), i + 1);this.threadArr[i].setPriority(7);this.threadArr[i].start();}}}//回調,更新UIif (listener != null)listener.onDownloadSize(this.downloadSize);// 通知目前已經下載完成的資料長度}//檔案下載完成刪除下載記錄。dbTools.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());}}/** * 列印日誌資訊 * * @param msg * 列印的日誌內容 */private static void print(String msg) {Log.i(TAG, msg);}/** * 下載檔案監聽 * * 主要用於回調。 */public interface DownloadProgressListener {public void onDownloadSize(int size);}}
package com.example.util;import java.io.IOException;import java.net.HttpURLConnection;import java.net.URL;/** * <p> * </p> * * @author xiangxm */public class Common {/** * 格式檔案大 * * @param volume * 檔案大小 * @return 格式化的字元 */public static String getVolume(long volume) {float num = 1.0F;String str = null;if (volume < 1024) {str = volume + "B";} else if (volume < 1048576) {num = num * volume / 1024;str = String.format("%.1f", num) + "K";} else if (volume < 1073741824) {num = num * volume / 1048576;str = String.format("%.1f", num) + "M";} else if (volume < 1099511627776L) {num = num * volume / 1073741824;str = String.format("%.1f", num) + "G";}return str;}/** * * 設定網路參數 */public static HttpURLConnection getHttpParams(URL httpUrl) {HttpURLConnection http;try {http = (HttpURLConnection) httpUrl.openConnection();http.setConnectTimeout(5 * 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", httpUrl.toString());http.setRequestProperty("Charset", "UTF-8");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");return http;} catch (IOException e) {e.printStackTrace();}return null;}}
原始碼:http://download.csdn.net/detail/xxm282828/7701071
看一下:
下一篇打算: 使用downloadManager實現下載,斷點續傳。