Android网络多线程断点续传下载

时间:2022-11-17 10:01:02

本示例介绍在Android平台下通过HTTP协议实现断点续传下载。

我们编写的是Andorid的HTTP协议多线程断点下载应用程序。直接使用单线程下载HTTP文件对我们来说是一件非常简单的事。那么,多线程断点需要什么功能?难在哪里?

1.多线程下载,

2.支持断点。

 

使用多线程的好处:使用多线程下载会提升文件下载的速度。那么多线程下载文件的过程是:

(1)首先获得下载文件的长度,然后设置本地文件的长度。

HttpURLConnection.getContentLength();//获取下载文件的长度

RandomAccessFile file = new RandomAccessFile("QQWubiSetup.exe","rwd");

file.setLength(filesize);//设置本地文件的长度


          (2)根据文件长度和线程数计算每条线程下载的数据长度和下载位置。

             如:文件的长度为6M,线程数为3,那么,每条线程下载的数据长度为2M,每条线程开始下载的位置如下图所示。

Android网络多线程断点续传下载

           例如10M大小,使用3个线程来下载,

               线程下载的数据长度   (10%3 == 0 ? 10/3:10/3+1) ,第1,2个线程下载长度是4M,第三个线程下载长度为2M

                下载开始位置:线程id*每条线程下载的数据长度 = ?

下载结束位置:(线程id+1)*每条线程下载的数据长度-1=?


          (3)使用Http的Range头字段指定每条线程从文件的什么位置开始下载,下载到什么位置为止,

                如:指定从文件的2M位置开始下载,下载到位置(4M-1byte)为止

           代码如下:HttpURLConnection.setRequestProperty("Range", "bytes=2097152-4194303");


          (4)保存文件,使用RandomAccessFile类指定每条线程从本地文件的什么位置开始写入数据。

RandomAccessFile threadfile = new RandomAccessFile("QQWubiSetup.exe ","rwd");

threadfile.seek(2097152);//从文件的什么位置开始写入数据

程序结构如下图所示:

Android网络多线程断点续传下载

string.xml文件中代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="hello">Hello World, MainActivity!</string>
  4. <string name="app_name">Android网络多线程断点下载</string>
  5. <string name="path">下载路径</string>
  6. <string name="downloadbutton">下载</string>
  7. <string name="sdcarderror">SDCard不存在或者写保护</string>
  8. <string name="success">下载完成</string>
  9. <string name="error">下载失败</string>
  10. </resources>

main.xml文件中代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <!-- 下载路径 -->
  7. <TextView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="@string/path"/>
  11. <EditText
  12. android:id="@+id/path"
  13. android:text="http://www.winrar.com.cn/download/wrar380sc.exe"
  14. android:layout_width="fill_parent"
  15. android:layout_height="wrap_content">
  16. </EditText>
  17. <!-- 下载按钮 -->
  18. <Button
  19. android:layout_width="wrap_content"
  20. android:layout_height="wrap_content"
  21. android:text="@string/downloadbutton"
  22. android:id="@+id/button"/>
  23. <!-- 进度条 -->
  24. <ProgressBar
  25. android:layout_width="fill_parent"
  26. android:layout_height="20dip"
  27. style="?android:attr/progressBarStyleHorizontal"
  28. android:id="@+id/downloadbar" />
  29. <TextView
  30. android:layout_width="fill_parent"
  31. android:layout_height="wrap_content"
  32. android:gravity="center"
  33. android:id="@+id/resultView" />
  34. </LinearLayout>

  AndroidManifest.xml文件中代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest
    xmlns:android="http://schemas.android.com/apk/res/android"    
     package="com.android.downloader"      android:versionCode="1"    
     android:versionName="1.0">
  3. <uses-sdk android:minSdkVersion="8" />
  4. <application android:icon="@drawable/icon" android:label="@string/app_name">
  5. <activity android:name=".MainActivity"
  6. android:label="@string/app_name">
  7. <intent-filter>
  8. <action android:name="android.intent.action.MAIN" />
  9. <category android:name="android.intent.category.LAUNCHER" />
  10. </intent-filter>
  11. </activity>
  12. </application>
  13. <!-- 在SDCard中创建与删除文件权限 -->
  14. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
  15. <!-- 往SDCard写入数据权限 -->
  16. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  17. <!-- 访问internet权限 -->
  18. <uses-permission android:name="android.permission.INTERNET"/>
  19. </manifest>

MainActivity中代码:

  1. package com.android.downloader;
  2. import java.io.File;
  3. import com.android.network.DownloadProgressListener;
  4. import com.android.network.FileDownloader;
  5. import android.app.Activity;
  6. import android.os.Bundle;
  7. import android.os.Environment;
  8. import android.os.Handler;
  9. import android.os.Message;
  10. import android.view.View;
  11. import android.widget.Button;
  12. import android.widget.EditText;
  13. import android.widget.ProgressBar;
  14. import android.widget.TextView;
  15. import android.widget.Toast;
  16. public class MainActivity extends Activity {
  17. private EditText downloadpathText;
  18. private TextView resultView;
  19. private ProgressBar progressBar;
  20. /**
  21. * 当Handler被创建会关联到创建它的当前线程的消息队列,该类用于往消息队列发送消息
  22. * 消息队列中的消息由当前线程内部进行处理
  23. */
  24. private Handler handler = new Handler(){
  25. @Override
  26. public void handleMessage(Message msg) {
  27. switch (msg.what) {
  28. case 1:
  29. progressBar.setProgress(msg.getData().getInt("size"));
  30. float num = (float)progressBar.getProgress()/(float)progressBar.getMax();
  31. int result = (int)(num*100);
  32. resultView.setText(result+ "%");
  33. if(progressBar.getProgress()==progressBar.getMax()){
  34. Toast.makeText(MainActivity.this, R.string.success, 1).show();
  35. }
  36. break;
  37. case -1:
  38. Toast.makeText(MainActivity.this, R.string.error, 1).show();
  39. break;
  40. }
  41. }
  42. };
  43. /** Called when the activity is first created. */
  44. @Override
  45. public void onCreate(Bundle savedInstanceState) {
  46. super.onCreate(savedInstanceState);
  47. setContentView(R.layout.main);
  48. downloadpathText = (EditText) this.findViewById(R.id.path);
  49. progressBar = (ProgressBar) this.findViewById(R.id.downloadbar);
  50. resultView = (TextView) this.findViewById(R.id.resultView);
  51. Button button = (Button) this.findViewById(R.id.button);
  52. button.setOnClickListener(new View.OnClickListener() {
  53. @Override
  54. public void onClick(View v) {
  55. // TODO Auto-generated method stub
  56. String path = downloadpathText.getText().toString();
  57. System.out.println(Environment.getExternalStorageState()+"------"+Environment.MEDIA_MOUNTED);
  58. if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  59. download(path, Environment.getExternalStorageDirectory());
  60. }else{
  61. Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();
  62. }
  63. }
  64. });
  65. }
  66. /**
  67. * 主线程(UI线程)
  68. * 对于显示控件的界面更新只是由UI线程负责,如果是在非UI线程更新控件的属性值,更新后的显示界面不会反映到屏幕上
  69. * @param path
  70. * @param savedir
  71. */
  72. private void download(final String path, final File savedir) {
  73. new Thread(new Runnable() {
  74. @Override
  75. public void run() {
  76. FileDownloader loader = new FileDownloader(MainActivity.this, path, savedir, 3);
  77. progressBar.setMax(loader.getFileSize());//设置进度条的最大刻度为文件的长度
  78. try {
  79. loader.download(new DownloadProgressListener() {
  80. @Override
  81. public void onDownloadSize(int size) {//实时获知文件已经下载的数据长度
  82. Message msg = new Message();
  83. msg.what = 1;
  84. msg.getData().putInt("size", size);
  85. handler.sendMessage(msg);//发送消息
  86. }
  87. });
  88. } catch (Exception e) {
  89. handler.obtainMessage(-1).sendToTarget();
  90. }
  91. }
  92. }).start();
  93. }
  94. }

DBOpenHelper中代码:

  1. package com.android.service;
  2. import android.content.Context;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.database.sqlite.SQLiteOpenHelper;
  5. public class DBOpenHelper extends SQLiteOpenHelper {
  6. private static final String DBNAME = "down.db";
  7. private static final int VERSION = 1;
  8. public DBOpenHelper(Context context) {
  9. super(context, DBNAME, null, VERSION);
  10. }
  11. @Override
  12. public void onCreate(SQLiteDatabase db) {
  13. db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id
    integer primary key autoincrement, downpath varchar(100), threadid
    INTEGER, downlength INTEGER)");
  14. }
  15. @Override
  16. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  17. db.execSQL("DROP TABLE IF EXISTS filedownlog");
  18. onCreate(db);
  19. }
  20. }

FileService中代码:

  1. package com.android.service;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import android.content.Context;
  5. import android.database.Cursor;
  6. import android.database.sqlite.SQLiteDatabase;
  7. public class FileService {
  8. private DBOpenHelper openHelper;
  9. public FileService(Context context) {
  10. openHelper = new DBOpenHelper(context);
  11. }
  12. /**
  13. * 获取每条线程已经下载的文件长度
  14. * @param path
  15. * @return
  16. */
  17. public Map<Integer, Integer> getData(String path){
  18. SQLiteDatabase db = openHelper.getReadableDatabase();
  19. Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[]{path});
  20. Map<Integer, Integer> data = new HashMap<Integer, Integer>();
  21. while(cursor.moveToNext()){
  22. data.put(cursor.getInt(0), cursor.getInt(1));
  23. }
  24. cursor.close();
  25. db.close();
  26. return data;
  27. }
  28. /**
  29. * 保存每条线程已经下载的文件长度
  30. * @param path
  31. * @param map
  32. */
  33. public void save(String path,  Map<Integer, Integer> map){//int threadid, int position
  34. SQLiteDatabase db = openHelper.getWritableDatabase();
  35. db.beginTransaction();
  36. try{
  37. for(Map.Entry<Integer, Integer> entry : map.entrySet()){
  38. db.execSQL("insert into filedownlog(downpath, threadid, downlength) values(?,?,?)",
  39. new Object[]{path, entry.getKey(), entry.getValue()});
  40. }
  41. db.setTransactionSuccessful();
  42. }finally{
  43. db.endTransaction();
  44. }
  45. db.close();
  46. }
  47. /**
  48. * 实时更新每条线程已经下载的文件长度
  49. * @param path
  50. * @param map
  51. */
  52. public void update(String path, Map<Integer, Integer> map){
  53. SQLiteDatabase db = openHelper.getWritableDatabase();
  54. db.beginTransaction();
  55. try{
  56. for(Map.Entry<Integer, Integer> entry : map.entrySet()){
  57. db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?",
  58. new Object[]{entry.getValue(), path, entry.getKey()});
  59. }
  60. db.setTransactionSuccessful();
  61. }finally{
  62. db.endTransaction();
  63. }
  64. db.close();
  65. }
  66. /**
  67. * 当文件下载完成后,删除对应的下载记录
  68. * @param path
  69. */
  70. public void delete(String path){
  71. SQLiteDatabase db = openHelper.getWritableDatabase();
  72. db.execSQL("delete from filedownlog where downpath=?", new Object[]{path});
  73. db.close();
  74. }
  75. }

DownloadProgressListener中代码:

  1. package com.android.network;
  2. public interface DownloadProgressListener {
  3. public void onDownloadSize(int size);
  4. }

FileDownloader中代码:

  1. package com.android.network;
  2. import java.io.File;
  3. import java.io.RandomAccessFile;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import java.util.LinkedHashMap;
  7. import java.util.Map;
  8. import java.util.UUID;
  9. import java.util.concurrent.ConcurrentHashMap;
  10. import java.util.regex.Matcher;
  11. import java.util.regex.Pattern;
  12. import com.android.service.FileService;
  13. import android.content.Context;
  14. import android.util.Log;
  15. public class FileDownloader {
  16. private static final String TAG = "FileDownloader";
  17. private Context context;
  18. private FileService fileService;
  19. /* 已下载文件长度 */
  20. private int downloadSize = 0;
  21. /* 原始文件长度 */
  22. private int fileSize = 0;
  23. /* 线程数 */
  24. private DownloadThread[] threads;
  25. /* 本地保存文件 */
  26. private File saveFile;
  27. /* 缓存各线程下载的长度*/
  28. private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();
  29. /* 每条线程下载的长度 */
  30. private int block;
  31. /* 下载路径  */
  32. private String downloadUrl;
  33. /**
  34. * 获取线程数
  35. */
  36. public int getThreadSize() {
  37. return threads.length;
  38. }
  39. /**
  40. * 获取文件大小
  41. * @return
  42. */
  43. public int getFileSize() {
  44. return fileSize;
  45. }
  46. /**
  47. * 累计已下载大小
  48. * @param size
  49. */
  50. protected synchronized void append(int size) {
  51. downloadSize += size;
  52. }
  53. /**
  54. * 更新指定线程最后下载的位置
  55. * @param threadId 线程id
  56. * @param pos 最后下载的位置
  57. */
  58. protected synchronized void update(int threadId, int pos) {
  59. this.data.put(threadId, pos);
  60. this.fileService.update(this.downloadUrl, this.data);
  61. }
  62. /**
  63. * 构建文件下载器
  64. * @param downloadUrl 下载路径
  65. * @param fileSaveDir 文件保存目录
  66. * @param threadNum 下载线程数
  67. */
  68. public FileDownloader(Context context, String downloadUrl, File fileSaveDir, int threadNum) {
  69. try {
  70. this.context = context;
  71. this.downloadUrl = downloadUrl;
  72. fileService = new FileService(this.context);
  73. URL url = new URL(this.downloadUrl);
  74. if(!fileSaveDir.exists()) fileSaveDir.mkdirs();
  75. this.threads = new DownloadThread[threadNum];
  76. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  77. conn.setConnectTimeout(5*1000);
  78. conn.setRequestMethod("GET");
  79. conn.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, */*");
  80. conn.setRequestProperty("Accept-Language", "zh-CN");
  81. conn.setRequestProperty("Referer", downloadUrl);
  82. conn.setRequestProperty("Charset", "UTF-8");
  83. conn.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)");
  84. conn.setRequestProperty("Connection", "Keep-Alive");
  85. conn.connect();
  86. printResponseHeader(conn);
  87. if (conn.getResponseCode()==200) {
  88. this.fileSize = conn.getContentLength();//根据响应获取文件大小
  89. if (this.fileSize <= 0) throw new RuntimeException("Unkown file size ");
  90. String filename = getFileName(conn);//获取文件名称
  91. this.saveFile = new File(fileSaveDir, filename);//构建保存文件
  92. Map<Integer, Integer> logdata = fileService.getData(downloadUrl);//获取下载记录
  93. if(logdata.size()>0){//如果存在下载记录
  94. for(Map.Entry<Integer, Integer> entry : logdata.entrySet())
  95. data.put(entry.getKey(), entry.getValue());//把各条线程已经下载的数据长度放入data中
  96. }
  97. if(this.data.size()==this.threads.length){//下面计算所有线程已经下载的数据长度
  98. for (int i = 0; i < this.threads.length; i++) {
  99. this.downloadSize += this.data.get(i+1);
  100. }
  101. print("已经下载的长度"+ this.downloadSize);
  102. }
  103. //计算每条线程下载的数据长度
  104. this.block = (this.fileSize %
    this.threads.length)==0? this.fileSize / this.threads.length :
    this.fileSize / this.threads.length + 1;
  105. }else{
  106. throw new RuntimeException("server no response ");
  107. }
  108. } catch (Exception e) {
  109. print(e.toString());
  110. throw new RuntimeException("don't connection this url");
  111. }
  112. }
  113. /**
  114. * 获取文件名
  115. * @param conn
  116. * @return
  117. */
  118. private String getFileName(HttpURLConnection conn) {
  119. String filename = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);
  120. if(filename==null || "".equals(filename.trim())){//如果获取不到文件名称
  121. for (int i = 0;; i++) {
  122. String mine = conn.getHeaderField(i);
  123. if (mine == null) break;
  124. if("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())){
  125. Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
  126. if(m.find()) return m.group(1);
  127. }
  128. }
  129. filename = UUID.randomUUID()+ ".tmp";//默认取一个文件名
  130. }
  131. return filename;
  132. }
  133. /**
  134. *  开始下载文件
  135. * @param listener 监听下载数量的变化,如果不需要了解实时下载的数量,可以设置为null
  136. * @return 已下载文件大小
  137. * @throws Exception
  138. */
  139. public int download(DownloadProgressListener listener) throws Exception{
  140. try {
  141. RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");
  142. if(this.fileSize>0) randOut.setLength(this.fileSize);
  143. randOut.close();
  144. URL url = new URL(this.downloadUrl);
  145. if(this.data.size() != this.threads.length){
  146. this.data.clear();
  147. for (int i = 0; i < this.threads.length; i++) {
  148. this.data.put(i+1, 0);//初始化每条线程已经下载的数据长度为0
  149. }
  150. }
  151. for (int i = 0; i < this.threads.length; i++) {//开启线程进行下载
  152. int downLength = this.data.get(i+1);
  153. if(downLength < this.block && this.downloadSize<this.fileSize){//判断线程是否已经完成下载,否则继续下载
  154. this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);
  155. this.threads[i].setPriority(7);
  156. this.threads[i].start();
  157. }else{
  158. this.threads[i] = null;
  159. }
  160. }
  161. this.fileService.save(this.downloadUrl, this.data);
  162. boolean notFinish = true;//下载未完成
  163. while (notFinish) {// 循环判断所有线程是否完成下载
  164. Thread.sleep(900);
  165. notFinish = false;//假定全部线程下载完成
  166. for (int i = 0; i < this.threads.length; i++){
  167. if (this.threads[i] != null && !this.threads[i].isFinish()) {//如果发现线程未完成下载
  168. notFinish = true;//设置标志为下载没有完成
  169. if(this.threads[i].getDownLength() == -1){//如果下载失败,再重新下载
  170. this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);
  171. this.threads[i].setPriority(7);
  172. this.threads[i].start();
  173. }
  174. }
  175. }
  176. if(listener!=null) listener.onDownloadSize(this.downloadSize);//通知目前已经下载完成的数据长度
  177. }
  178. fileService.delete(this.downloadUrl);
  179. } catch (Exception e) {
  180. print(e.toString());
  181. throw new Exception("file download fail");
  182. }
  183. return this.downloadSize;
  184. }
  185. /**
  186. * 获取Http响应头字段
  187. * @param http
  188. * @return
  189. */
  190. public static Map<String, String> getHttpResponseHeader(HttpURLConnection http) {
  191. Map<String, String> header = new LinkedHashMap<String, String>();
  192. for (int i = 0;; i++) {
  193. String mine = http.getHeaderField(i);
  194. if (mine == null) break;
  195. header.put(http.getHeaderFieldKey(i), mine);
  196. }
  197. return header;
  198. }
  199. /**
  200. * 打印Http头字段
  201. * @param http
  202. */
  203. public static void printResponseHeader(HttpURLConnection http){
  204. Map<String, String> header = getHttpResponseHeader(http);
  205. for(Map.Entry<String, String> entry : header.entrySet()){
  206. String key = entry.getKey()!=null ? entry.getKey()+ ":" : "";
  207. print(key+ entry.getValue());
  208. }
  209. }
  210. private static void print(String msg){
  211. Log.i(TAG, msg);
  212. }
  213. }

DownloadThread 中代码:

  1. package com.android.network;
  2. import java.io.File;
  3. import java.io.InputStream;
  4. import java.io.RandomAccessFile;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import android.util.Log;
  8. public class DownloadThread extends Thread {
  9. private static final String TAG = "DownloadThread";
  10. private File saveFile;
  11. private URL downUrl;
  12. private int block;
  13. /* 下载开始位置  */
  14. private int threadId = -1;
  15. private int downLength;
  16. private boolean finish = false;
  17. private FileDownloader downloader;
  18. public DownloadThread(FileDownloader downloader, URL downUrl, File saveFile, int block, int downLength, int threadId) {
  19. this.downUrl = downUrl;
  20. this.saveFile = saveFile;
  21. this.block = block;
  22. this.downloader = downloader;
  23. this.threadId = threadId;
  24. this.downLength = downLength;
  25. }
  26. @Override
  27. public void run() {
  28. if(downLength < block){//未下载完成
  29. try {
  30. HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();
  31. http.setConnectTimeout(5 * 1000);
  32. http.setRequestMethod("GET");
  33. 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, */*");
  34. http.setRequestProperty("Accept-Language", "zh-CN");
  35. http.setRequestProperty("Referer", downUrl.toString());
  36. http.setRequestProperty("Charset", "UTF-8");
  37. int startPos = block * (threadId - 1) + downLength;//开始位置
  38. int endPos = block * threadId -1;//结束位置
  39. http.setRequestProperty("Range", "bytes=" + startPos + "-"+ endPos);//设置获取实体数据的范围
  40. 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)");
  41. http.setRequestProperty("Connection", "Keep-Alive");
  42. InputStream inStream = http.getInputStream();
  43. byte[] buffer = new byte[1024];
  44. int offset = 0;
  45. print("Thread " + this.threadId + " start download from position "+ startPos);
  46. RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");
  47. threadfile.seek(startPos);
  48. while ((offset = inStream.read(buffer, 0, 1024)) != -1) {
  49. threadfile.write(buffer, 0, offset);
  50. downLength += offset;
  51. downloader.update(this.threadId, downLength);
  52. downloader.append(offset);
  53. }
  54. threadfile.close();
  55. inStream.close();
  56. print("Thread " + this.threadId + " download finish");
  57. this.finish = true;
  58. } catch (Exception e) {
  59. this.downLength = -1;
  60. print("Thread "+ this.threadId+ ":"+ e);
  61. }
  62. }
  63. }
  64. private static void print(String msg){
  65. Log.i(TAG, msg);
  66. }
  67. /**
  68. * 下载是否完成
  69. * @return
  70. */
  71. public boolean isFinish() {
  72. return finish;
  73. }
  74. /**
  75. * 已经下载的内容大小
  76. * @return 如果返回值为-1,代表下载失败
  77. */
  78. public long getDownLength() {
  79. return downLength;
  80. }
  81. }

运行效果如下:       

Android网络多线程断点续传下载

          完毕。^_^