多線程下載
樓主三年磨劍(當然不是磨著一把劍),傾血奉獻Android多線程下載Demo。有的人就問了“怎麼寫來寫去還是Demo?”,因為老哥我實在太忙了,
每天寫一點,寫到現在也才寫了個下載器,也就差下載管理類就是個完整的模塊了。對於新手學習這已經足夠了,不對,是完全足夠了。
這不僅僅隻是一個簡單的Demo,這絕對是你前所未見的商業級別的範例,集支持多線程下載,斷點續傳,隻使用wifi網絡下載,顯示下載速度,人性化提示
及超強的容錯機製多功能於一體,絕對的實用,絕對的專業。
當然我寫這個是為了下載apk的,大家稍微改一改就可以寫成更通用的下載器。唯一有點不足的地方就是在Android上使用RandomAccessFile在創建大文件的時候
速度有些慢,導致前幾秒的進度都為0。不知道有沒有人可以幫我解決這個問題。
下麵給出關鍵代碼。
- package com.h3c.DownloadEngine;
- 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 java.util.ArrayList;
- import android.content.Context;
- import android.os.Environment;
- import android.util.Log;
- import com.h3c.DownloadEngine.common.DownloaderErrorException;
- import com.h3c.DownloadEngine.common.EngineConstants;
- import com.h3c.DownloadEngine.common.EngineUtil;
- import com.h3c.DownloadEngine.common.EngineVariable;
- import com.h3c.DownloadEngine.db.EngineDBOperator;
- import com.h3c.DownloadEngine.entity.DownloadBean;
- public class Downloader {
- private final static String TAG = "Downloader";
- private final static byte[] lock_getFileSize = new byte[1];
- private final static byte[] lock_refresh_progress = new byte[1];
- private int mThreadCount = 4;// 默認子線程數為4個
- private int bufferSize = 1024 * 16; // 16K 一個塊
- private DownloadBean mBean;// 注意,這裏是dwonloader的bean不是其subBean
- private Context mContext;
- private DownloadEngineCallback mCallback;
- private EngineDBOperator mDBOper;
- private int mDoneThreadCount = 0;// 完成的線程數
- private int mState = EngineConstants.DOWNLOAD_STATE_INIT;// 下載器狀態
- private ArrayList<DownloadBean> mBeans = new ArrayList<DownloadBean>(
- mThreadCount);
- public Downloader(DownloadBean bean, Context context,
- DownloadEngineCallback callback) throws DownloaderErrorException {
- this.mBean = bean;
- this.mContext = context;
- this.mCallback = callback;
- this.mDBOper = EngineDBOperator.getInstance(context);
- if (this.mDBOper != null) {
- if (this.mDBOper.isHasDownloadTaskByUrl(bean.url)) {// 如果此任務已經存放進數據庫
- getDownloaderInfoFromDB(bean);
- } else {// 插入信息至數據庫
- addDownloaderInfoToDB(bean);
- }
- } else {
- callBackError("Downloader錯誤,可能是EngineDBOperator為Null.");
- throw new DownloaderErrorException(
- "Downloader錯誤,可能是EngineDBOperator為Null.");
- }
- }
- public DownloadBean getDownloaderInfo() {
- return mBean;
- }
- public int getDownloaderState() {
- return mState;
- }
- /**
- * 請求初始化
- *
- * @param state
- */
- protected void setDownloaderState(int state) {
- mState = state;
- if (state == EngineConstants.DOWNLOAD_STATE_INIT) {
- mBean.currentPosition = 0;
- }
- }
- /**
- * 加入下載信息進入數據庫,此方法用於剛剛初始化Downloader,且數據庫中沒有該任務的時候
- *
- * @param bean
- * @throws DownloaderErrorException
- */
- private void addDownloaderInfoToDB(DownloadBean bean)
- throws DownloaderErrorException {
- if (mState != EngineConstants.DOWNLOAD_STATE_INIT
- && mState != EngineConstants.DOWNLOAD_STATE_STOP
- && mState != EngineConstants.DOWNLOAD_STATE_ERROR) {
- callBackError("這個任務已經加入到數據庫中了");
- throw new DownloaderErrorException("這個任務已經加入到數據庫中了");
- }
- if (mDBOper != null) {
- long fileSize = bean.fileSize;
- if (mBeans.size() > 0) {
- mBeans.clear();
- }
- try {
- if (fileSize > 0) {// 判斷傳入的fileSize大小,如果大於0,就不用從網絡中獲取,直接初始化N個子下載器
- if (!hasSpaceInSDCard()) {
- return;
- }
- long range = fileSize / mThreadCount;// 文件分段值
- for (int i = 0; i < mThreadCount - 1; i++) {
- DownloadBean subBean = (DownloadBean) bean.clone();
- subBean.threadId = i;
- subBean.startPosition = i * range;
- subBean.endPosition = (i + 1) * range - 1;
- mBeans.add(subBean);
- }
- DownloadBean subBean = (DownloadBean) bean.clone();
- subBean.threadId = mThreadCount - 1;
- subBean.startPosition = (mThreadCount - 1) * range;
- subBean.endPosition = fileSize - 1;
- mBeans.add(subBean);
- } else {// 如果等於0,就直接初始化N個0大小的子下載器
- for (int n = 0; n < mThreadCount - 1; n++) {
- DownloadBean subBean = (DownloadBean) bean.clone();
- subBean.threadId = n;
- mBeans.add(subBean);
- }
- DownloadBean subBean = (DownloadBean) bean.clone();
- subBean.threadId = mThreadCount - 1;
- mBeans.add(subBean);
- }
- mDBOper.addDownloadTask(mBeans);
- if (bean.fileSize > 0) {// 如果文件大小已經獲取就進入等待狀態
- mState = EngineConstants.DOWNLOAD_STATE_WAITTING;// 下載器進入等待狀態
- } else {// 文件大小未獲取就開啟線程去獲取文件大小並更新子下載器中的內容
- new Thread(new Runnable() {
- @Override
- public void run() {
- boolean flag = false;
- synchronized (lock_getFileSize) {
- flag = getFileSizeByNetwork(mBean);
- }
- if (flag) {
- mState = EngineConstants.DOWNLOAD_STATE_WAITTING;// 下載器進入等待狀態
- } else {
- Log.e(TAG, "從網絡中獲取文件大小失敗 1");
- }
- }
- }).start();
- }
- } catch (CloneNotSupportedException e) {
- e.printStackTrace();
- }
- } else {
- callBackError("addDownloaderInfoToDB錯誤,可能是EngineDBOperator為Null.");
- throw new DownloaderErrorException(
- "addDownloaderInfoToDB錯誤,可能是EngineDBOperator為Null.");
- }
- }
- /**
- * 從數據庫中讀取下載器信息
- *
- * @param bean
- * @throws DownloaderErrorException
- */
- private void getDownloaderInfoFromDB(DownloadBean bean)
- throws DownloaderErrorException {
- if (mDBOper != null) {
- mBeans.clear();
- mBeans = mDBOper.getDownloadTaskByUrl(bean.url);
- mBean.currentPosition = 0;
- mBean.fileSize = 0;
- mThreadCount = mBeans.size();
- for (DownloadBean subBean : mBeans) {
- mBean.currentPosition += subBean.currentPosition;
- if (subBean.fileSize > mBean.fileSize) {
- mBean.fileSize = subBean.fileSize;
- }
- }
- if (mBean.fileSize < 1) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- boolean flag = false;
- synchronized (lock_getFileSize) {
- flag = getFileSizeByNetwork(mBean);
- }
- if (flag) {
- mState = EngineConstants.DOWNLOAD_STATE_WAITTING;// 下載器進入等待狀態
- } else {
- Log.e(TAG, "從網絡中獲取文件大小失敗 2");
- }
- }
- }).start();
- } else {
- mState = EngineConstants.DOWNLOAD_STATE_WAITTING;// 下載器進入等待狀態
- }
- } else {
- callBackError("getDownloaderInfoFromDB Error,May be EngineDBOperator is Null.");
- throw new DownloaderErrorException(
- "getDownloaderInfoFromDB Error,May be EngineDBOperator is Null.");
- }
- }
- /**
- * 從網絡中獲取文件大小,並更新listBeans
- */
- private boolean getFileSizeByNetwork(DownloadBean bean) {
- HttpURLConnection connection = null;
- long fileSize = bean.fileSize;
- try {
- if (fileSize <= 0) {// 如果沒有傳入文件大小就從網絡中獲取
- URL url = new URL(bean.url);
- connection = (HttpURLConnection) url.openConnection();
- connection.setConnectTimeout(5000);
- connection.setReadTimeout(8000);
- if (android.os.Build.VERSION.SDK_INT > 10) {// 規避2.x上因為加入setRM導致連接超時的bug
- connection.setRequestMethod("HEAD");// head
- }
- int resopnseCode = connection.getResponseCode();
- if (resopnseCode != 200 && resopnseCode != 206) {
- callBackError("http返回碼不正確:" + resopnseCode);
- return false;
- }
- // 獲得文件大小
- fileSize = connection.getContentLength();
- mBean.fileSize = fileSize;
- if (fileSize <= 0) {
- callBackError("無法從服務器上獲得文件大小" + fileSize);
- return false;
- }
- // if (connection.getHeaderField("Content-Range") == null) {
- // Log.e(TAG, "服務器不支持斷點續傳");
- // mThreadCount = 1;
- // }
- // 如果沒有存儲空間了
- if (!hasSpaceInSDCard()) {
- return false;
- }
- long range = fileSize / mThreadCount;// 文件分段值
- // 更新listBean
- for (int i = 0; i < mThreadCount - 1; i++) {
- DownloadBean subBean = mBeans.get(i);
- subBean.fileSize = fileSize;
- subBean.startPosition = i * range;
- subBean.endPosition = (i + 1) * range - 1;
- }
- DownloadBean subBean = mBeans.get(mThreadCount - 1);
- subBean.fileSize = fileSize;
- subBean.startPosition = (mThreadCount - 1) * range;
- subBean.endPosition = fileSize - 1;
- // 更新數據庫
- if (mDBOper != null) {
- mDBOper.updateTaskCompleteSize(mBeans, mBean.url);
- } else {
- callBackError("getFileSizeByNetwork錯誤,可能是EngineDBOperator is Null.");
- throw new DownloaderErrorException(
- "getFileSizeByNetwork錯誤,可能是EngineDBOperator is Null.");
- }
- return true;
- } else {// 文件有大小就直接退出
- return true;
- }
- } catch (Exception e) {
- callBackError("從服務器獲取文件大小超時");
- e.printStackTrace();
- } finally {
- if (connection != null) {
- connection.disconnect();
- }
- }
- return false;
- }
- /**
- * 開始下載,可能多次調用
- */
- public void startDownloader() {
- if (mState == EngineConstants.DOWNLOAD_STATE_DOWNLOADING) {// 如果正在下載就return
- return;
- }
- if (mBean == null) {
- callBackError("下載器沒有初始化");
- return;
- }
- File file = new File(mBean.savePath);
- File parentDirectory = file.getParentFile();
- if (!parentDirectory.exists()) {
- parentDirectory.mkdirs();
- }
- if (!file.exists()) {
- try {
- file.createNewFile();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (mBeans.size() < 1) {// 防止由於發生錯誤導致清空了mBeans列表,但是又重新開始了任務,所有要再次初始化mBeans
- try {
- addDownloaderInfoToDB(mBean);
- } catch (DownloaderErrorException e) {
- e.printStackTrace();
- return;
- }
- }
- /**
- * 隻有獲得文件大小後才會開始下載
- */
- synchronized (lock_getFileSize) {
- if (mState == EngineConstants.DOWNLOAD_STATE_INIT) {// 獲取文件大小失敗,重新獲取
- boolean flag = getFileSizeByNetwork(mBean);
- if (!flag) {
- callBackError("獲取文件大小失敗");
- return;
- }
- }
- }
- mState = EngineConstants.DOWNLOAD_STATE_DOWNLOADING;
- mDBOper.removePauseFileByUrl(mBean.url);// 從暫停列表中移除
- mDoneThreadCount = 0;// 初始化完成線程數
- for (DownloadBean bean : mBeans) {
- if (bean.currentPosition < (bean.endPosition - bean.startPosition)) {// 如果該線程屬於沒有下載完成的
- HamalThread hamalThread = new HamalThread(bean);
- hamalThread.start();
- } else {// 已經完成的線程不需要重新創建
- mDoneThreadCount++;
- }
- }
- if (mDoneThreadCount == mThreadCount) {// 下載完成
- downloaderDone();
- }
- }
- private class HamalThread extends Thread {
- private int threadId;
- private long startPos;
- private long endPos;
- private long compeleteSize;
- private String urlstr;
- public HamalThread(DownloadBean bean) {
- this.threadId = bean.threadId;
- this.startPos = bean.startPosition;
- this.endPos = bean.endPosition;
- this.compeleteSize = bean.currentPosition;
- this.urlstr = bean.url;
- }
- @Override
- public void run() {
- HttpURLConnection connection = null;
- RandomAccessFile randomAccessFile = null;
- InputStream is = null;
- try {
- URL url = new URL(urlstr);
- connection = (HttpURLConnection) url.openConnection();
- connection.setConnectTimeout(5000);
- connection.setReadTimeout(8000);
- connection.setRequestMethod("GET");
- if (mThreadCount > 1) {// 多線程下載
- // 設置範圍,格式為Range:bytes x-y;
- connection.setRequestProperty("Range", "bytes="
- + (startPos + compeleteSize) + "-" + endPos);
- }
- randomAccessFile = new RandomAccessFile(mBean.savePath, "rwd");
- randomAccessFile.seek(startPos + compeleteSize);
- // 將要下載的文件寫到保存在保存路徑下的文件中
- is = connection.getInputStream();
- byte[] buffer = new byte[bufferSize];
- int length = -1;
- EngineUtil eUtil = EngineUtil.getInstance();
- if (EngineVariable.SUPPORT_NETWORK_TYPE == EngineConstants.DOWNLOAD_NETWORK_ONLYWIFI) {// 如果隻能是3G下載
- if (eUtil.getNetworkType() != EngineConstants.NETWORK_STATE_WIFI) {// 且當前網絡不是Wifi
- interruptDownloader();
- return;
- }
- }
- while ((length = is.read(buffer)) != -1) {
- // 網絡判斷
- if (EngineVariable.SUPPORT_NETWORK_TYPE == EngineConstants.DOWNLOAD_NETWORK_ONLYWIFI) {// 如果隻能是3G下載
- if (eUtil.getNetworkType() != EngineConstants.NETWORK_STATE_WIFI) {// 且當前網絡不是Wifi
- interruptDownloader();
- return;
- }
- }
- randomAccessFile.write(buffer, 0, length);
- compeleteSize += length;
- synchronized (lock_refresh_progress) {
- mBean.currentPosition += length;
- }
- // 更新數據庫中的下載信息
- mDBOper.updateTaskCompleteSize(threadId, compeleteSize,
- urlstr);
- if (mState == EngineConstants.DOWNLOAD_STATE_PAUSE
- || mState == EngineConstants.DOWNLOAD_STATE_INTERRUPT
- || mState == EngineConstants.DOWNLOAD_STATE_STOP
- || mState == EngineConstants.DOWNLOAD_STATE_ERROR) {// 暫停
- return;
- }
- }
- // 該子線程下載完成
- mDoneThreadCount++;
- } catch (Exception e) {
- Log.e(TAG, "下載途中斷掉了連接...");
- interruptDownloader();
- e.printStackTrace();
- } finally {
- try {
- is.close();
- randomAccessFile.close();
- connection.disconnect();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- if (mDoneThreadCount == mThreadCount) {
- downloaderDone();
- }
- }
- }
- /**
- * 獲取下載進度
- *
- * @return
- */
- public int getProgress() {
- if (mBean.fileSize < 1) {
- return 0;
- }
- return (int) (mBean.currentPosition * 100 / mBean.fileSize);
- }
- /**
- * 暫停下載
- */
- public void pauseDownloader() {
- mState = EngineConstants.DOWNLOAD_STATE_PAUSE;
- mDBOper.addPauseFile(mBean.url, mBean.packageName, mBean.fileId);
- }
- /**
- * 中斷下載(非人為的暫停)
- */
- private void interruptDownloader() {
- mState = EngineConstants.DOWNLOAD_STATE_INTERRUPT;
- }
- /**
- * 結束下載
- */
- public void stopDownloader() {
- mState = EngineConstants.DOWNLOAD_STATE_STOP;
- mBean.currentPosition = 0;
- removeDownloaderInfo(mBean.url);
- }
- /**
- * 清除下載的信息
- *
- * @param urlstr
- */
- private void removeDownloaderInfo(String urlstr) {
- mDBOper.deleteDownloadTaskByUrl(urlstr);
- mDBOper.removePauseFileByUrl(urlstr);
- mBeans.clear();
- }
- /**
- * 下載完成
- */
- private void downloaderDone() {
- mState = EngineConstants.DOWNLOAD_STATE_DONE;
- mBean.doneTime = System.currentTimeMillis();
- mCallback.callbackWhenDownloadTaskListener(mState, mBean,
- mBean.fileName + "下載完成");
- removeDownloaderInfo(mBean.url);
- mDBOper.addCompleteTask(mBean);// 將完成信息保存至數據庫
- }
- /**
- * 出現錯誤時候回調
- *
- * @param info
- */
- private void callBackError(String info) {
- mState = EngineConstants.DOWNLOAD_STATE_ERROR;
- mCallback.callbackWhenDownloadTaskListener(mState, mBean, info);
- removeDownloaderInfo(mBean.url);
- }
- /**
- * 判斷SD卡上是否留有足夠的空間
- */
- private boolean hasSpaceInSDCard() {
- if (mBean.fileSize > EngineUtil.getInstance().getFreeSpaceAtDirectory(
- Environment.getExternalStorageDirectory().getAbsolutePath())) {
- callBackError("存儲卡空間不夠");
- return false;
- }
- return true;
- }
- }
歡迎吐槽,歡迎提供建議,歡迎提供改進方法。
整個架構詳見源碼,絕對值得你下載收藏!這一切都是免費的,對,你不要懷疑,商業級別的源碼都是免費的。
如果你覺得好,請幫忙下載源碼下載。
源碼:https://download.csdn.net/detail/h3c4lenovo/5987789
最後更新:2017-04-03 12:55:18