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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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来看。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 的集合类主要包括 List、Set、Map 等,它们都是用来存储数据的。List 是有序的集合,可以存储重复的元素;Set 是无序的集合,不允许存储重复的元素;Map 是一种键值对存储的数据结构,可以通过键来获取值。 Android 的 IO 流主要用来进行文件的读写操作。Java 中的 IO 流主要分为字节流和字符流。字节流主要用来操作二进制文件,字符流主要用来操作文本文件。在 Android 中,FileInputStream 和 FileOutputStream 是字节流,用于读写二进制文件;FileReader 和 FileWriter 是字符流,用于读写文本文件Android 的多线程编程可以使用 Java 中的 Thread 类来实现。但是在 Android 中,应该使用异步任务 AsyncTask 来进行多线程编程。这是因为在 Android 中,主线程负责界面的绘制和事件响应,如果在主线程中进行耗时操作,会导致界面卡顿,用户体验不好。而 AsyncTask 可以在后台线程中执行耗时操作,同时也可以更新 UI。 Android 的断点上传下载一般使用 HttpURLConnection 来实现。在上传文件时,可以使用 HttpURLConnection 的 setChunkedStreamingMode 方法来进行分块上传,从而支持断点续传。在下载文件时,可以使用 HttpURLConnection 获取输入流,然后使用 RandomAccessFile 进行随机访问,从而实现断点续传Android 的线程池可以使用 Java 中的 Executor 和 ExecutorService 接口来实现。可以通过 ThreadPoolExecutor 类来创建线程池。线程池可以有效地利用线程资源,提高程序的效率。同时也可以控制线程的数量,避免线程数量过多导致程序崩溃。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值