Android網絡編程 --斷點續傳下載文件

Android網絡編程 --斷點續傳下載文件

2014年2月28日 2月最後一天

前言:關於斷點續傳下載文件,這個我好幾個月之前面試的時候就遇到過,那時我確實迷惑了一下,Android開發分兩種,一種是界面開發,一種是研發應用型,面試官問過我屬於哪一種,我記得那次面試對我打擊很大,因爲它證明了我對Android還不夠熟悉,水平還不到家,反正感覺被面試官鄙視了。不過到現在我已經不那麼想了,不管是界面開發還是研發應用,靠的都是動手能力,能做出東西人才是有用之人,面試主要看你對技術有沒有概念,實際開發中誰管你會不會那個技術,反正你給我把效果做出來就行了,做不出東西就給我滾蛋,所以經驗對應屆生來說是一大詬病,所以建議在大學的雛鳥們多動手做點東西出來,而不是死磕大學那些無用的課程。

廢話多了一點,下面我就來介紹本篇博客的技術要點:
HTTP協議,我想上過計算機網絡課程的童鞋肯定不陌生,但是誰又能說自己能把它實際運用上了,只有在實際項目開發的時候纔會用到。Http算是Android網絡中最常用到的網絡協議了,客戶端通過http通信與服務器進行數據交互,GET方法和POST方法想必是再熟悉不過了,本篇博客介紹一個比較實用的技術,斷點續傳下載,光看這個名字就感覺挺高大上,確實是,想實現它需要對http協議有一定的瞭解,並且對多線程機制比較熟悉,還有就是Android中異步更新UI的原理不能讓程序出現卡頓的現象。
在說http斷點續傳之前需要重點了解http協議頭部的Range字段
Range 

   用於請求頭中,指定第一個字節的位置和最後一個字節的位置,一般格式:

   Range:(unit=first byte pos)-[last byte pos] 

比如你要請求下載一個MP3文件,url爲:http://abv.cn/music/光輝歲月.mp3

你需要通過http發送get請求,請求頭字段可能如下

GET /music/%E5%85%89%E8%BE%89%E5%B2%81%E6%9C%88.mp3 HTTP/1.1
Host: abv.cn
Connection: keep-alive
Accept-Encoding: identity;q=1, *;q=0
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.16 50.63 Safari/537.36
Accept: */*
Referer: http://abv.cn/music/%E5%85%89%E8%BE%89%E5%B2%81%E6%9C%88.mp3
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6
Range: bytes=0-// 請求內容字節範圍
如果直接請求的話,自然字節從0開始了。
響應頭部字段:
HTTP/1.1 206 Partial Content
Date: Tue, 25 Feb 2014 06:05:26 GMT
Server: Apache/2.4.3 (Unix) OpenSSL/1.0.1c PHP/5.4.7
Last-Modified: Sun, 23 Feb 2014 12:53:00 GMT
ETag: "49aa24-4f31255b92300"
Accept-Ranges: bytes
Content-Length: 4827684// 這個表示文件大小
Content-Range: bytes 0-4827683/4827684// 文件字節範圍

Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: audio/mpeg


關於其他字段的含義,我在這裏就不解釋了,自己動手查去,哪個不懂就查哪個。上面很直觀的展示了請求很響應的內容。

那麼斷點續傳的原理就是通過http請求你想下載內容的字節範圍,假如之前已經下載了一部分,但你有事需要暫停下載,那麼下次下載的時候你接着後面繼續下載就可以了。
但再實際開發中,可能需要下載比較大的文件,並且不能下載太久,這時候我們需要利用多線程來分段下載我們需要的內容。下面是在Android平臺下實現的多線程斷點續傳下載:
http://download.csdn.net/detail/wwj_748/6975041,源碼已經給你們準備好了。

代碼中註釋已經很清楚,小巫在這裏就多說了。
/MultiThreadDownload/src/com/wwj/download/db/DBOpenHelper.java
數據庫幫助類,用於創建保存下載進度的表
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.wwj.download.db;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.   
  7. public class DBOpenHelper extends SQLiteOpenHelper {  
  8.     private static final String DBNAME = "eric.db";  
  9.     private static final int VERSION = 1;  
  10.   
  11.     public DBOpenHelper(Context context) {  
  12.         super(context, DBNAME, null, VERSION);  
  13.     }  
  14.   
  15.     @Override  
  16.     public void onCreate(SQLiteDatabase db) {  
  17.         // 創建filedownlog表  
  18.         db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, downlength INTEGER)");  
  19.     }  
  20.   
  21.     @Override  
  22.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  23.         db.execSQL("DROP TABLE IF EXISTS filedownlog");  
  24.         onCreate(db);  
  25.     }  
  26. }  


/MultiThreadDownload/src/com/wwj/net/download/FileDownloader.java
文件下載器
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.wwj.net.download;  
  2.   
  3. import java.io.File;  
  4. import java.io.RandomAccessFile;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.util.LinkedHashMap;  
  8. import java.util.Map;  
  9. import java.util.UUID;  
  10. import java.util.concurrent.ConcurrentHashMap;  
  11. import java.util.regex.Matcher;  
  12. import java.util.regex.Pattern;  
  13.   
  14. import android.content.Context;  
  15. import android.util.Log;  
  16.   
  17. /** 
  18.  * 文件下載器 
  19.  *  
  20.  */  
  21. public class FileDownloader {  
  22.     private static final String TAG = "FileDownloader";  
  23.     private Context context;  
  24.     private FileService fileService;  
  25.     /* 停止下載 */  
  26.     private boolean exit;  
  27.     /* 已下載文件長度 */  
  28.     private int downloadSize = 0;  
  29.     /* 原始文件長度 */  
  30.     private int fileSize = 0;  
  31.     /* 線程數 */  
  32.     private DownloadThread[] threads;  
  33.     /* 本地保存文件 */  
  34.     private File saveFile;  
  35.     /* 緩存各線程下載的長度 */  
  36.     private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();  
  37.     /* 每條線程下載的長度 */  
  38.     private int block;  
  39.     /* 下載路徑 */  
  40.     private String downloadUrl;  
  41.   
  42.     /** 
  43.      * 獲取線程數 
  44.      */  
  45.     public int getThreadSize() {  
  46.         return threads.length;  
  47.     }  
  48.   
  49.     /** 
  50.      * 退出下載 
  51.      */  
  52.     public void exit() {  
  53.         this.exit = true;  
  54.     }  
  55.   
  56.     public boolean getExit() {  
  57.         return this.exit;  
  58.     }  
  59.   
  60.     /** 
  61.      * 獲取文件大小 
  62.      *  
  63.      * @return 
  64.      */  
  65.     public int getFileSize() {  
  66.         return fileSize;  
  67.     }  
  68.   
  69.     /** 
  70.      * 累計已下載大小 
  71.      *  
  72.      * @param size 
  73.      */  
  74.     protected synchronized void append(int size) {  
  75.         downloadSize += size;  
  76.     }  
  77.   
  78.     /** 
  79.      * 更新指定線程最後下載的位置 
  80.      *  
  81.      * @param threadId 
  82.      *            線程id 
  83.      * @param pos 
  84.      *            最後下載的位置 
  85.      */  
  86.     protected synchronized void update(int threadId, int pos) {  
  87.         this.data.put(threadId, pos);  
  88.         this.fileService.update(this.downloadUrl, threadId, pos);  
  89.     }  
  90.   
  91.     /** 
  92.      * 構建文件下載器 
  93.      *  
  94.      * @param downloadUrl 
  95.      *            下載路徑 
  96.      * @param fileSaveDir 
  97.      *            文件保存目錄 
  98.      * @param threadNum 
  99.      *            下載線程數 
  100.      */  
  101.     public FileDownloader(Context context, String downloadUrl,  
  102.             File fileSaveDir, int threadNum) {  
  103.         try {  
  104.             this.context = context;  
  105.             this.downloadUrl = downloadUrl;  
  106.             fileService = new FileService(this.context);  
  107.             URL url = new URL(this.downloadUrl);  
  108.             if (!fileSaveDir.exists()) // 判斷目錄是否存在,如果不存在,創建目錄  
  109.                 fileSaveDir.mkdirs();  
  110.             this.threads = new DownloadThread[threadNum];// 實例化線程數組  
  111.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  112.             conn.setConnectTimeout(5 * 1000);  
  113.             conn.setRequestMethod("GET");  
  114.             conn.setRequestProperty(  
  115.                     "Accept",  
  116.                     "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, */*");  
  117.             conn.setRequestProperty("Accept-Language""zh-CN");  
  118.             conn.setRequestProperty("Referer", downloadUrl);  
  119.             conn.setRequestProperty("Charset""UTF-8");  
  120.             conn.setRequestProperty(  
  121.                     "User-Agent",  
  122.                     "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)");  
  123.             conn.setRequestProperty("Connection""Keep-Alive");  
  124.             conn.connect(); // 連接  
  125.             printResponseHeader(conn);  
  126.             if (conn.getResponseCode() == 200) { // 響應成功  
  127.                 this.fileSize = conn.getContentLength();// 根據響應獲取文件大小  
  128.                 if (this.fileSize <= 0)  
  129.                     throw new RuntimeException("Unkown file size ");  
  130.   
  131.                 String filename = getFileName(conn);// 獲取文件名稱  
  132.                 this.saveFile = new File(fileSaveDir, filename);// 構建保存文件  
  133.                 Map<Integer, Integer> logdata = fileService  
  134.                         .getData(downloadUrl);// 獲取下載記錄  
  135.                 if (logdata.size() > 0) {// 如果存在下載記錄  
  136.                     for (Map.Entry<Integer, Integer> entry : logdata.entrySet())  
  137.                         data.put(entry.getKey(), entry.getValue());// 把各條線程已經下載的數據長度放入data中  
  138.                 }  
  139.                 if (this.data.size() == this.threads.length) {// 下面計算所有線程已經下載的數據總長度  
  140.                     for (int i = 0; i < this.threads.length; i++) {  
  141.                         this.downloadSize += this.data.get(i + 1);  
  142.                     }  
  143.                     print("已經下載的長度" + this.downloadSize);  
  144.                 }  
  145.                 // 計算每條線程下載的數據長度  
  146.                 this.block = (this.fileSize % this.threads.length) == 0 ? this.fileSize  
  147.                         / this.threads.length  
  148.                         : this.fileSize / this.threads.length + 1;  
  149.             } else {  
  150.                 throw new RuntimeException("server no response ");  
  151.             }  
  152.         } catch (Exception e) {  
  153.             print(e.toString());  
  154.             throw new RuntimeException("don't connection this url");  
  155.         }  
  156.     }  
  157.   
  158.     /**  
  159.      * 獲取文件名  
  160.      */  
  161.     private String getFileName(HttpURLConnection conn) {  
  162.         String filename = this.downloadUrl.substring(this.downloadUrl  
  163.                 .lastIndexOf('/') + 1);  
  164.         if (filename == null || "".equals(filename.trim())) {// 如果獲取不到文件名稱  
  165.             for (int i = 0;; i++) {  
  166.                 String mine = conn.getHeaderField(i);  
  167.                 if (mine == null)  
  168.                     break;  
  169.                 if ("content-disposition".equals(conn.getHeaderFieldKey(i)  
  170.                         .toLowerCase())) {  
  171.                     Matcher m = Pattern.compile(".*filename=(.*)").matcher(  
  172.                             mine.toLowerCase());  
  173.                     if (m.find())  
  174.                         return m.group(1);  
  175.                 }  
  176.             }  
  177.             filename = UUID.randomUUID() + ".tmp";// 默認取一個文件名  
  178.         }  
  179.         return filename;  
  180.     }  
  181.   
  182.     /** 
  183.      * 開始下載文件 
  184.      *  
  185.      * @param listener 
  186.      *            監聽下載數量的變化,如果不需要了解實時下載的數量,可以設置爲null 
  187.      * @return 已下載文件大小 
  188.      * @throws Exception 
  189.      */  
  190.     public int download(DownloadProgressListener listener) throws Exception {  
  191.         try {  
  192.             RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");  
  193.             if (this.fileSize > 0)  
  194.                 randOut.setLength(this.fileSize); // 預分配fileSize大小  
  195.             randOut.close();  
  196.             URL url = new URL(this.downloadUrl);  
  197.             if (this.data.size() != this.threads.length) {// 如果原先未曾下載或者原先的下載線程數與現在的線程數不一致  
  198.                 this.data.clear();  
  199.                 for (int i = 0; i < this.threads.length; i++) {  
  200.                     this.data.put(i + 10);// 初始化每條線程已經下載的數據長度爲0  
  201.                 }  
  202.                 this.downloadSize = 0;  
  203.             }  
  204.             for (int i = 0; i < this.threads.length; i++) {// 開啓線程進行下載  
  205.                 int downLength = this.data.get(i + 1);  
  206.                 if (downLength < this.block  
  207.                         && this.downloadSize < this.fileSize) {// 判斷線程是否已經完成下載,否則繼續下載  
  208.                     this.threads[i] = new DownloadThread(this, url,  
  209.                             this.saveFile, this.block, this.data.get(i + 1),  
  210.                             i + 1);  
  211.                     this.threads[i].setPriority(7); // 設置線程優先級  
  212.                     this.threads[i].start();  
  213.                 } else {  
  214.                     this.threads[i] = null;  
  215.                 }  
  216.             }  
  217.             fileService.delete(this.downloadUrl);// 如果存在下載記錄,刪除它們,然後重新添加  
  218.             fileService.save(this.downloadUrl, this.data);  
  219.             boolean notFinish = true;// 下載未完成  
  220.             while (notFinish) {// 循環判斷所有線程是否完成下載  
  221.                 Thread.sleep(900);  
  222.                 notFinish = false;// 假定全部線程下載完成  
  223.                 for (int i = 0; i < this.threads.length; i++) {  
  224.                     if (this.threads[i] != null && !this.threads[i].isFinish()) {// 如果發現線程未完成下載  
  225.                         notFinish = true;// 設置標誌爲下載沒有完成  
  226.                         if (this.threads[i].getDownLength() == -1) {// 如果下載失敗,再重新下載  
  227.                             this.threads[i] = new DownloadThread(this, url,  
  228.                                     this.saveFile, this.block,  
  229.                                     this.data.get(i + 1), i + 1);  
  230.                             this.threads[i].setPriority(7);  
  231.                             this.threads[i].start();  
  232.                         }  
  233.                     }  
  234.                 }  
  235.                 if (listener != null)  
  236.                     listener.onDownloadSize(this.downloadSize);// 通知目前已經下載完成的數據長度  
  237.             }  
  238.             if (downloadSize == this.fileSize)  
  239.                 fileService.delete(this.downloadUrl);// 下載完成刪除記錄  
  240.         } catch (Exception e) {  
  241.             print(e.toString());  
  242.             throw new Exception("file download error");  
  243.         }  
  244.         return this.downloadSize;  
  245.     }  
  246.   
  247.     /** 
  248.      * 獲取Http響應頭字段 
  249.      *  
  250.      * @param http 
  251.      * @return 
  252.      */  
  253.     public static Map<String, String> getHttpResponseHeader(  
  254.             HttpURLConnection http) {  
  255.         Map<String, String> header = new LinkedHashMap<String, String>();  
  256.         for (int i = 0;; i++) {  
  257.             String mine = http.getHeaderField(i);  
  258.             if (mine == null)  
  259.                 break;  
  260.             header.put(http.getHeaderFieldKey(i), mine);  
  261.         }  
  262.         return header;  
  263.     }  
  264.   
  265.     /** 
  266.      * 打印Http頭字段 
  267.      *  
  268.      * @param http 
  269.      */  
  270.     public static void printResponseHeader(HttpURLConnection http) {  
  271.         Map<String, String> header = getHttpResponseHeader(http);  
  272.         for (Map.Entry<String, String> entry : header.entrySet()) {  
  273.             String key = entry.getKey() != null ? entry.getKey() + ":" : "";  
  274.             print(key + entry.getValue());  
  275.         }  
  276.     }  
  277.   
  278.     private static void print(String msg) {  
  279.         Log.i(TAG, msg);  
  280.     }  
  281. }  


/MultiThreadDownload/src/com/wwj/net/download/FileService.java
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.wwj.net.download;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import android.content.Context;  
  7. import android.database.Cursor;  
  8. import android.database.sqlite.SQLiteDatabase;  
  9.   
  10. import com.wwj.download.db.DBOpenHelper;  
  11.   
  12. /** 
  13.  * 業務bean 
  14.  *  
  15.  */  
  16. public class FileService {  
  17.     private DBOpenHelper openHelper;  
  18.   
  19.     public FileService(Context context) {  
  20.         openHelper = new DBOpenHelper(context);  
  21.     }  
  22.   
  23.     /** 
  24.      * 獲取每條線程已經下載的文件長度 
  25.      *  
  26.      * @param path 
  27.      * @return 
  28.      */  
  29.     public Map<Integer, Integer> getData(String path) {  
  30.         SQLiteDatabase db = openHelper.getReadableDatabase();  
  31.         Cursor cursor = db  
  32.                 .rawQuery(  
  33.                         "select threadid, downlength from filedownlog where downpath=?",  
  34.                         new String[] { path });  
  35.         Map<Integer, Integer> data = new HashMap<Integer, Integer>();  
  36.         while (cursor.moveToNext()) {  
  37.             data.put(cursor.getInt(0), cursor.getInt(1));  
  38.         }  
  39.         cursor.close();  
  40.         db.close();  
  41.         return data;  
  42.     }  
  43.   
  44.     /** 
  45.      * 保存每條線程已經下載的文件長度 
  46.      *  
  47.      * @param path 
  48.      * @param map 
  49.      */  
  50.     public void save(String path, Map<Integer, Integer> map) {// int threadid,  
  51.                                                                 // int position  
  52.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  53.         db.beginTransaction();  
  54.         try {  
  55.             for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
  56.                 db.execSQL(  
  57.                         "insert into filedownlog(downpath, threadid, downlength) values(?,?,?)",  
  58.                         new Object[] { path, entry.getKey(), entry.getValue() });  
  59.             }  
  60.             db.setTransactionSuccessful();  
  61.         } finally {  
  62.             db.endTransaction();  
  63.         }  
  64.         db.close();  
  65.     }  
  66.   
  67.     /** 
  68.      * 實時更新每條線程已經下載的文件長度 
  69.      *  
  70.      * @param path 
  71.      * @param map 
  72.      */  
  73.     public void update(String path, int threadId, int pos) {  
  74.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  75.         db.execSQL(  
  76.                 "update filedownlog set downlength=? where downpath=? and threadid=?",  
  77.                 new Object[] { pos, path, threadId });  
  78.         db.close();  
  79.     }  
  80.   
  81.     /** 
  82.      * 當文件下載完成後,刪除對應的下載記錄 
  83.      *  
  84.      * @param path 
  85.      */  
  86.     public void delete(String path) {  
  87.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  88.         db.execSQL("delete from filedownlog where downpath=?",  
  89.                 new Object[] { path });  
  90.         db.close();  
  91.     }  
  92.   
  93. }  



/MultiThreadDownload/src/com/wwj/net/download/DownloadThread.java
下載線程類
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.wwj.net.download;  
  2.   
  3. import java.io.File;  
  4. import java.io.InputStream;  
  5. import java.io.RandomAccessFile;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import android.util.Log;  
  10.   
  11. public class DownloadThread extends Thread {  
  12.     private static final String TAG = "DownloadThread";  
  13.     private File saveFile;  
  14.     private URL downUrl;  
  15.     private int block;  
  16.     /* 下載開始位置 */  
  17.     private int threadId = -1;  
  18.     private int downLength;  
  19.     private boolean finish = false;  
  20.     private FileDownloader downloader;  
  21.   
  22.     public DownloadThread(FileDownloader downloader, URL downUrl,  
  23.             File saveFile, int block, int downLength, int threadId) {  
  24.         this.downUrl = downUrl;  
  25.         this.saveFile = saveFile;  
  26.         this.block = block;  
  27.         this.downloader = downloader;  
  28.         this.threadId = threadId;  
  29.         this.downLength = downLength;  
  30.     }  
  31.   
  32.     @Override  
  33.     public void run() {  
  34.         if (downLength < block) {// 未下載完成  
  35.             try {  
  36.                 HttpURLConnection http = (HttpURLConnection) downUrl  
  37.                         .openConnection();  
  38.                 http.setConnectTimeout(5 * 1000); // 設置連接超時  
  39.                 http.setRequestMethod("GET"); // 設置請求方法,這裏是“GET”  
  40.                 // 瀏覽器可接受的MIME類型  
  41.                 http.setRequestProperty(  
  42.                         "Accept",  
  43.                         "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, */*");  
  44.                 http.setRequestProperty("Accept-Language""zh-CN"); // 瀏覽器所希望的語言種類,當服務器能夠提供一種以上的語言版本時要用到  
  45.                 http.setRequestProperty("Referer", downUrl.toString());// 包含一個URL,用戶從該URL代表的頁面出發訪問當前請求的頁面。  
  46.                 http.setRequestProperty("Charset""UTF-8"); // 字符集  
  47.                 int startPos = block * (threadId - 1) + downLength;// 開始位置  
  48.                 int endPos = block * threadId - 1;// 結束位置  
  49.                 http.setRequestProperty("Range""bytes=" + startPos + "-"  
  50.                         + endPos);// 設置獲取實體數據的範圍  
  51.                 // 瀏覽器類型,如果Servlet返回的內容與瀏覽器類型有關則該值非常有用。  
  52.                 http.setRequestProperty(  
  53.                         "User-Agent",  
  54.                         "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)");  
  55.                 http.setRequestProperty("Connection""Keep-Alive"); // 設置爲持久連接  
  56.   
  57.                 // 得到輸入流  
  58.                 InputStream inStream = http.getInputStream();  
  59.                 byte[] buffer = new byte[1024];  
  60.                 int offset = 0;  
  61.                 print("Thread " + this.threadId  
  62.                         + " start download from position " + startPos);  
  63.                 // 隨機訪問文件  
  64.                 RandomAccessFile threadfile = new RandomAccessFile(  
  65.                         this.saveFile, "rwd");  
  66.                 // 定位到pos位置  
  67.                 threadfile.seek(startPos);  
  68.                 while (!downloader.getExit()  
  69.                         && (offset = inStream.read(buffer, 01024)) != -1) {  
  70.                     // 寫入文件  
  71.                     threadfile.write(buffer, 0, offset);  
  72.                     downLength += offset; // 累加下載的大小  
  73.                     downloader.update(this.threadId, downLength); // 更新指定線程下載最後的位置  
  74.                     downloader.append(offset); // 累加已下載大小  
  75.                 }  
  76.                 threadfile.close();  
  77.                 inStream.close();  
  78.                 print("Thread " + this.threadId + " download finish");  
  79.                 this.finish = true;  
  80.             } catch (Exception e) {  
  81.                 this.downLength = -1;  
  82.                 print("Thread " + this.threadId + ":" + e);  
  83.             }  
  84.         }  
  85.     }  
  86.   
  87.     private static void print(String msg) {  
  88.         Log.i(TAG, msg);  
  89.     }  
  90.   
  91.     /**  
  92.      * 下載是否完成  
  93.      *   
  94.      * @return  
  95.      */  
  96.     public boolean isFinish() {  
  97.         return finish;  
  98.     }  
  99.   
  100.     /** 
  101.      * 已經下載的內容大小 
  102.      *  
  103.      * @return 如果返回值爲-1,代表下載失敗 
  104.      */  
  105.     public long getDownLength() {  
  106.         return downLength;  
  107.     }  
  108. }  


/MultiThreadDownload/src/com/wwj/net/download/DownloadProgressListener.java
下載進度接口
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.wwj.net.download;  
  2.   
  3.   
  4. public interface DownloadProgressListener {  
  5.     public void onDownloadSize(int size);  
  6. }  


/MultiThreadDownload/src/com/wwj/download/MainActivity.java
界面
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.wwj.download;  
  2.   
  3. import java.io.File;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.net.URLEncoder;  
  6.   
  7. import android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.os.Environment;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.view.View;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;  
  15. import android.widget.ProgressBar;  
  16. import android.widget.TextView;  
  17. import android.widget.Toast;  
  18.   
  19. import com.wwj.net.download.DownloadProgressListener;  
  20. import com.wwj.net.download.FileDownloader;  
  21.   
  22. public class MainActivity extends Activity {  
  23.     private static final int PROCESSING = 1;  
  24.     private static final int FAILURE = -1;  
  25.   
  26.     private EditText pathText; // url地址  
  27.     private TextView resultView;  
  28.     private Button downloadButton;  
  29.     private Button stopButton;  
  30.     private ProgressBar progressBar;  
  31.   
  32.     private Handler handler = new UIHandler();  
  33.   
  34.     private final class UIHandler extends Handler {  
  35.         public void handleMessage(Message msg) {  
  36.             switch (msg.what) {  
  37.             case PROCESSING: // 更新進度  
  38.                 progressBar.setProgress(msg.getData().getInt("size"));  
  39.                 float num = (float) progressBar.getProgress()  
  40.                         / (float) progressBar.getMax();  
  41.                 int result = (int) (num * 100); // 計算進度  
  42.                 resultView.setText(result + "%");  
  43.                 if (progressBar.getProgress() == progressBar.getMax()) { // 下載完成  
  44.                     Toast.makeText(getApplicationContext(), R.string.success,  
  45.                             Toast.LENGTH_LONG).show();  
  46.                 }  
  47.                 break;  
  48.             case FAILURE: // 下載失敗  
  49.                 Toast.makeText(getApplicationContext(), R.string.error,  
  50.                         Toast.LENGTH_LONG).show();  
  51.                 break;  
  52.             }  
  53.         }  
  54.     }  
  55.   
  56.     @Override  
  57.     protected void onCreate(Bundle savedInstanceState) {  
  58.         super.onCreate(savedInstanceState);  
  59.         setContentView(R.layout.main);  
  60.         pathText = (EditText) findViewById(R.id.path);  
  61.         resultView = (TextView) findViewById(R.id.resultView);  
  62.         downloadButton = (Button) findViewById(R.id.downloadbutton);  
  63.         stopButton = (Button) findViewById(R.id.stopbutton);  
  64.         progressBar = (ProgressBar) findViewById(R.id.progressBar);  
  65.         ButtonClickListener listener = new ButtonClickListener();  
  66.         downloadButton.setOnClickListener(listener);  
  67.         stopButton.setOnClickListener(listener);  
  68.     }  
  69.   
  70.     private final class ButtonClickListener implements View.OnClickListener {  
  71.         @Override  
  72.         public void onClick(View v) {  
  73.             switch (v.getId()) {  
  74.             case R.id.downloadbutton: // 開始下載  
  75.                 // http://abv.cn/music/光輝歲月.mp3,可以換成其他文件下載的鏈接  
  76.                 String path = pathText.getText().toString();  
  77.                 String filename = path.substring(path.lastIndexOf('/') + 1);  
  78.   
  79.                 try {  
  80.                     // URL編碼(這裏是爲了將中文進行URL編碼)  
  81.                     filename = URLEncoder.encode(filename, "UTF-8");  
  82.                 } catch (UnsupportedEncodingException e) {  
  83.                     e.printStackTrace();  
  84.                 }  
  85.   
  86.                 path = path.substring(0, path.lastIndexOf("/") + 1) + filename;  
  87.                 if (Environment.getExternalStorageState().equals(  
  88.                         Environment.MEDIA_MOUNTED)) {  
  89.                     // File savDir =  
  90.                     // Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);  
  91.                     // 保存路徑  
  92.                     File savDir = Environment.getExternalStorageDirectory();  
  93.                     download(path, savDir);  
  94.                 } else {  
  95.                     Toast.makeText(getApplicationContext(),  
  96.                             R.string.sdcarderror, Toast.LENGTH_LONG).show();  
  97.                 }  
  98.                 downloadButton.setEnabled(false);  
  99.                 stopButton.setEnabled(true);  
  100.                 break;  
  101.             case R.id.stopbutton: // 暫停下載  
  102.                 exit();  
  103.                 Toast.makeText(getApplicationContext(),  
  104.                         "Now thread is Stopping!!", Toast.LENGTH_LONG).show();  
  105.                 downloadButton.setEnabled(true);  
  106.                 stopButton.setEnabled(false);  
  107.                 break;  
  108.             }  
  109.         }  
  110.   
  111.         /* 
  112.          * 由於用戶的輸入事件(點擊button, 觸摸屏幕....)是由主線程負責處理的,如果主線程處於工作狀態, 
  113.          * 此時用戶產生的輸入事件如果沒能在5秒內得到處理,系統就會報“應用無響應”錯誤。 
  114.          * 所以在主線程裏不能執行一件比較耗時的工作,否則會因主線程阻塞而無法處理用戶的輸入事件, 
  115.          * 導致“應用無響應”錯誤的出現。耗時的工作應該在子線程裏執行。 
  116.          */  
  117.         private DownloadTask task;  
  118.   
  119.         private void exit() {  
  120.             if (task != null)  
  121.                 task.exit();  
  122.         }  
  123.   
  124.         private void download(String path, File savDir) {  
  125.             task = new DownloadTask(path, savDir);  
  126.             new Thread(task).start();  
  127.         }  
  128.   
  129.         /** 
  130.          *  
  131.          * UI控件畫面的重繪(更新)是由主線程負責處理的,如果在子線程中更新UI控件的值,更新後的值不會重繪到屏幕上 
  132.          * 一定要在主線程裏更新UI控件的值,這樣才能在屏幕上顯示出來,不能在子線程中更新UI控件的值 
  133.          *  
  134.          */  
  135.         private final class DownloadTask implements Runnable {  
  136.             private String path;  
  137.             private File saveDir;  
  138.             private FileDownloader loader;  
  139.   
  140.             public DownloadTask(String path, File saveDir) {  
  141.                 this.path = path;  
  142.                 this.saveDir = saveDir;  
  143.             }  
  144.   
  145.             /** 
  146.              * 退出下載 
  147.              */  
  148.             public void exit() {  
  149.                 if (loader != null)  
  150.                     loader.exit();  
  151.             }  
  152.   
  153.             DownloadProgressListener downloadProgressListener = new DownloadProgressListener() {  
  154.                 @Override  
  155.                 public void onDownloadSize(int size) {  
  156.                     Message msg = new Message();  
  157.                     msg.what = PROCESSING;  
  158.                     msg.getData().putInt("size", size);  
  159.                     handler.sendMessage(msg);  
  160.                 }  
  161.             };  
  162.   
  163.             public void run() {  
  164.                 try {  
  165.                     // 實例化一個文件下載器  
  166.                     loader = new FileDownloader(getApplicationContext(), path,  
  167.                             saveDir, 3);  
  168.                     // 設置進度條最大值  
  169.                     progressBar.setMax(loader.getFileSize());  
  170.                     loader.download(downloadProgressListener);  
  171.                 } catch (Exception e) {  
  172.                     e.printStackTrace();  
  173.                     handler.sendMessage(handler.obtainMessage(FAILURE)); // 發送一條空消息對象  
  174.                 }  
  175.             }  
  176.         }  
  177.     }  
  178.   
  179. }  


以上就是所有核心代碼了,權限和佈局文件我就不貼了,自己可以下我提供的demo來看。

發佈了6 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章