android多線程斷點下載
作者:網(wǎng)絡(luò)整理 
  實現(xiàn)android 上面多線程斷點續(xù)傳下載 ,支持暫停,記憶任務(wù)。
 源碼簡介
實現(xiàn)android 上面多線程斷點續(xù)傳下載 ,支持暫停,記憶任務(wù)。
源碼運行截圖
源碼片段
- try {
 - HttpURLConnection http = (HttpURLConnection) downUrl
 - .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(, null); // 設(shè)置客戶端可以接受的返回數(shù)據(jù)類型
 - http.setRequestProperty("Accept-Language", "zh-CN");
 - http.setRequestProperty("Referer", downUrl.toString());// 設(shè)置請求的來源,便于對訪問來源進行統(tǒng)計
 - http.setRequestProperty("Charset", "UTF-8");
 - // 計算該線程下載的開始位置
 - int startPos = block * (threadId - 1) + downloadedLength;
 - /**
 - * 每塊結(jié)束的位置(***一塊需特殊處理,因為不能平均分配每塊大下,***一塊可能會有余數(shù))
 - */
 - //int endPosition = (i + 1) != threadCount ? ((i + 1) * blockSize - 1): fileSize;
 - // 計算該線程下載的結(jié)束位置
 - int endPos = threadId!=threadCount? (block *threadId):fileSize;
 - // 設(shè)置獲取實體數(shù)據(jù)的范圍,如果超過了實體數(shù)據(jù)的大小會自動返回實際的數(shù)據(jù)大小
 - 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");
 - // 獲取遠程連接的輸入流
 - InputStream inStream = http.getInputStream();
 - // 設(shè)置本地數(shù)據(jù)緩存的大小為1M
 - byte[] buffer = new byte[1024];
 - // 設(shè)置每次讀取的數(shù)據(jù)量
 - int offset = 0;
 - // 打印該線程開始下載的位置
 - print("Thread " + this.threadId
 - + " starts to download from position " + startPos);
 - RandomAccessFile threadFile = new RandomAccessFile(
 - this.saveFile, "rwd");
 - // 文件指針指向開始下載的位置
 - threadFile.seek(startPos);
 
源碼鏈接:http://down.51cto.com/data/1980815
責(zé)任編輯:chenqingxiang 
                    來源:
                    網(wǎng)絡(luò)整理
 
















 
 
 







 
 
 
 