[Android实例] Android之断点续传下载

在我们做开发的时候经常遇到的就是下载了,现在下载的方法有很多很多,那么怎么做到断点续传下载呢!很多人都头疼这个问题,如果我们没有很好的逻辑真不是很容易解决啊。我参考了一下前辈们的资料了整理了一个项目,能实现多个文件的同时下载。
断点续传下载,顾名思义,那就是我们在一次下载未结束时,退出下载,第二次下载时会接着第一次下载的进度继续下载。那么怎么记录第一次下载的数据呢,这里肯定就要用到数据库了。下面就是我创建数据库的一个SQLiteOpenHelper类。用来首次运行时创建数据库。
DBHelper.java

  1. package com.icss.DBHelper;
  2. import android.content.Context;
  3. import android.database.sqlite.SQLiteDatabase;
  4. import android.database.sqlite.SQLiteOpenHelper;
  5. /**
  6. * 建立一个数据库帮助类
  7. */
  8. public class DBHelper extends SQLiteOpenHelper {
  9. // download.db-->数据库名
  10. public DBHelper(Context context) {
  11. super(context, "download.db", null, 1);
  12. }
  13. /**
  14. * 在download.db数据库下创建一个download_info表存储下载信息
  15. */
  16. @Override
  17. public void onCreate(SQLiteDatabase db) {
  18. db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, "
  19. + "start_pos integer, end_pos integer, compelete_size integer,url char)");
  20. }
  21. @Override
  22. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  23. }
  24. }

复制代码

下面看主界面的布局,在这里,我只设计了一个ListView来显示下载的音乐的名称,和一个开始下载按钮和一个暂停按钮。
布局文件如下:
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" android:layout_width="fill_parent"
  4. android:layout_height="fill_parent" android:weightSum="1">
  5. <ListView android:id="@android:id/list" android:layout_height="wrap_content"
  6. android:layout_width="match_parent" android:layout_weight="0.70"></ListView>
  7. </LinearLayout>

复制代码

list_item.xml:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_height="fill_parent" android:id="@+id/linearLayout1"
  3. android:layout_width="fill_parent" android:orientation="vertical">
  4. <LinearLayout android:layout_width="fill_parent"
  5. android:id="@+id/linearLayout2" android:layout_height="wrap_content"
  6. android:orientation="horizontal" android:layout_marginBottom="5dip">
  7. <TextView android:layout_width="fill_parent"
  8. android:layout_height="wrap_content" android:layout_weight="1"
  9. android:id="@+id/tv_resouce_name" />
  10. <Button android:layout_width="fill_parent"
  11. android:layout_height="wrap_content" android:layout_weight="1"
  12. android:text="下载" android:id="@+id/btn_start" android:onClick="startDownload" />
  13. <Button android:layout_width="fill_parent"
  14. android:layout_height="wrap_content" android:layout_weight="1"
  15. android:text="暂停" android:id="@+id/btn_pause" android:onClick="pauseDownload" />
  16. </LinearLayout>
  17. </LinearLayout>

复制代码

我们要定义一个记录在下载时各个时期的数据的类,这里我创建了一个DownloadInfo类来记录。代码如下:
DownloadInfo:

  1. package com.icss.entity;
  2. public class DownloadInfo {
  3. private int threadId;// 下载器id
  4. private int startPos;// 开始点
  5. private int endPos;// 结束点
  6. private int compeleteSize;// 完成度
  7. private String url;// 下载器网络标识
  8. public DownloadInfo(int threadId, int startPos, int endPos,
  9. int compeleteSize, String url) {
  10. super();
  11. this.threadId = threadId;
  12. this.startPos = startPos;
  13. this.endPos = endPos;
  14. this.compeleteSize = compeleteSize;
  15. this.url = url;
  16. }
  17. public int getThreadId() {
  18. return threadId;
  19. }
  20. public void setThreadId(int threadId) {
  21. this.threadId = threadId;
  22. }
  23. public int getStartPos() {
  24. return startPos;
  25. }
  26. public void setStartPos(int startPos) {
  27. this.startPos = startPos;
  28. }
  29. public int getEndPos() {
  30. return endPos;
  31. }
  32. public void setEndPos(int endPos) {
  33. this.endPos = endPos;
  34. }
  35. public int getCompeleteSize() {
  36. return compeleteSize;
  37. }
  38. public void setCompeleteSize(int compeleteSize) {
  39. this.compeleteSize = compeleteSize;
  40. }
  41. public String getUrl() {
  42. return url;
  43. }
  44. public void setUrl(String url) {
  45. this.url = url;
  46. }
  47. @Override
  48. public String toString() {
  49. return "DownloadInfo [threadId=" + threadId
  50. + ", startPos=" + startPos + ", endPos=" + endPos
  51. + ", compeleteSize=" + compeleteSize +"]";
  52. }
  53. }

复制代码

在下载时,我们有进度条来显示进度,怎么确定进度条的进度,大小和起始位置呢?这里我定义了一个LoadInfo类来记录下载器详细信息。代码如下:
LoadInfo:

  1. package com.icss.entity;
  2. public class LoadInfo {
  3. public int fileSize;// 文件大小
  4. private int complete;// 完成度
  5. private String urlstring;// 下载器标识
  6. public LoadInfo() {
  7. super();
  8. // TODO Auto-generated constructor stub
  9. }
  10. public LoadInfo(int fileSize, int complete, String urlstring) {
  11. super();
  12. this.fileSize = fileSize;
  13. this.complete = complete;
  14. this.urlstring = urlstring;
  15. }
  16. public int getFileSize() {
  17. return fileSize;
  18. }
  19. public void setFileSize(int fileSize) {
  20. this.fileSize = fileSize;
  21. }
  22. public int getComplete() {
  23. return complete;
  24. }
  25. public void setComplete(int complete) {
  26. this.complete = complete;
  27. }
  28. public String getUrlstring() {
  29. return urlstring;
  30. }
  31. public void setUrlstring(String urlstring) {
  32. this.urlstring = urlstring;
  33. }
  34. @Override
  35. public String toString() {
  36. return "LoadInfo [fileSize=" + fileSize + ", complete=" + complete
  37. + ", urlstring=" + urlstring + "]";
  38. }
  39. }

复制代码

下面是最最重要的一步,那就是定义一个下载器来进行下载了,这里我就不多说,具体解释在代码中都有注解,供大家研究参考。
Downloader:

  1. package com.icss.service;
  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 java.util.ArrayList;
  8. import java.util.List;
  9. import com.icss.dao.Dao;
  10. import com.icss.entity.DownloadInfo;
  11. import com.icss.entity.LoadInfo;
  12. import android.content.Context;
  13. import android.os.Handler;
  14. import android.os.Message;
  15. import android.util.Log;
  16. public class Downloader {
  17. private String urlstr;// 下载的地址
  18. private String localfile;// 保存路径
  19. private int threadcount;// 线程数
  20. private Handler mHandler;// 消息处理器
  21. private Dao dao;// 工具类
  22. private int fileSize;// 所要下载的文件的大小
  23. private List<DownloadInfo> infos;// 存放下载信息类的集合
  24. private static final int INIT = 1;// 定义三种下载的状态:初始化状态,正在下载状态,暂停状态
  25. private static final int DOWNLOADING = 2;
  26. private static final int PAUSE = 3;
  27. private int state = INIT;
  28. public Downloader(String urlstr, String localfile, int threadcount,
  29. Context context, Handler mHandler) {
  30. this.urlstr = urlstr;
  31. this.localfile = localfile;
  32. this.threadcount = threadcount;
  33. this.mHandler = mHandler;
  34. dao = new Dao(context);
  35. }
  36. /**
  37. * 判断是否正在下载
  38. */
  39. public boolean isdownloading() {
  40. return state == DOWNLOADING;
  41. }
  42. /**
  43. * 得到downloader里的信息 首先进行判断是否是第一次下载,如果是第一次就要进行初始化,并将下载器的信息保存到数据库中
  44. * 如果不是第一次下载,那就要从数据库中读出之前下载的信息(起始位置,结束为止,文件大小等),并将下载信息返回给下载器
  45. */
  46. public LoadInfo getDownloaderInfors() {
  47. if (isFirst(urlstr)) {
  48. init();
  49. int range = fileSize / threadcount;
  50. infos = new ArrayList<DownloadInfo>();
  51. for (int i = 0; i < threadcount - 1; i++) {
  52. DownloadInfo info = new DownloadInfo(i, i * range, (i + 1)
  53. * range - 1, 0, urlstr);
  54. infos.add(info);
  55. }
  56. DownloadInfo info = new DownloadInfo(threadcount - 1,
  57. (threadcount - 1) * range, fileSize - 1, 0, urlstr);
  58. infos.add(info);
  59. // 保存infos中的数据到数据库
  60. dao.saveInfos(infos);
  61. // 创建一个LoadInfo对象记载下载器的具体信息
  62. LoadInfo loadInfo = new LoadInfo(fileSize, 0, urlstr);
  63. return loadInfo;
  64. } else {
  65. // 得到数据库中已有的urlstr的下载器的具体信息
  66. infos = dao.getInfos(urlstr);
  67. Log.v("TAG", "not isFirst size=" + infos.size());
  68. int size = 0;
  69. int compeleteSize = 0;
  70. for (DownloadInfo info : infos) {
  71. compeleteSize += info.getCompeleteSize();
  72. size += info.getEndPos() - info.getStartPos() + 1;
  73. }
  74. return new LoadInfo(size, compeleteSize, urlstr);
  75. }
  76. }
  77. /**
  78. */
  79. private void init() {
  80. try {
  81. URL url = new URL(urlstr);
  82. HttpURLConnection connection = (HttpURLConnection) url
  83. .openConnection();
  84. connection.setConnectTimeout(5000);
  85. connection.setRequestMethod("GET");
  86. fileSize = connection.getContentLength();
  87. File file = new File(localfile);
  88. if (!file.exists()) {
  89. file.createNewFile();
  90. }
  91. // 本地访问文件
  92. RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
  93. accessFile.setLength(fileSize);
  94. accessFile.close();
  95. connection.disconnect();
  96. } catch (Exception e) {
  97. e.printStackTrace();
  98. }
  99. }
  100. /**
  101. * 判断是否是第一次 下载
  102. */
  103. private boolean isFirst(String urlstr) {
  104. return dao.isHasInfors(urlstr);
  105. }
  106. /**
  107. * 114 * 利用线程开始下载数据 115
  108. */
  109. public void download() {
  110. if (infos != null) {
  111. if (state == DOWNLOADING)
  112. return;
  113. state = DOWNLOADING;
  114. for (DownloadInfo info : infos) {
  115. new MyThread(info.getThreadId(), info.getStartPos(),
  116. info.getEndPos(), info.getCompeleteSize(),
  117. info.getUrl()).start();
  118. }
  119. }
  120. }
  121. public class MyThread extends Thread {
  122. private int threadId;
  123. private int startPos;
  124. private int endPos;
  125. private int compeleteSize;
  126. private String urlstr;
  127. public MyThread(int threadId, int startPos, int endPos,
  128. int compeleteSize, String urlstr) {
  129. this.threadId = threadId;
  130. this.startPos = startPos;
  131. this.endPos = endPos;
  132. this.compeleteSize = compeleteSize;
  133. this.urlstr = urlstr;
  134. }
  135. @Override
  136. public void run() {
  137. HttpURLConnection connection = null;
  138. RandomAccessFile randomAccessFile = null;
  139. InputStream is = null;
  140. try {
  141. URL url = new URL(urlstr);
  142. connection = (HttpURLConnection) url.openConnection();
  143. connection.setConnectTimeout(5000);
  144. connection.setRequestMethod("GET");
  145. // 设置范围,格式为Range:bytes x-y;
  146. connection.setRequestProperty("Range", "bytes="
  147. + (startPos + compeleteSize) + "-" + endPos);
  148. randomAccessFile = new RandomAccessFile(localfile, "rwd");
  149. randomAccessFile.seek(startPos + compeleteSize);
  150. // 将要下载的文件写到保存在保存路径下的文件中
  151. is = connection.getInputStream();
  152. byte[] buffer = new byte[4096];
  153. int length = -1;
  154. while ((length = is.read(buffer)) != -1) {
  155. randomAccessFile.write(buffer, 0, length);
  156. compeleteSize += length;
  157. // 更新数据库中的下载信息
  158. dao.updataInfos(threadId, compeleteSize, urlstr);
  159. // 用消息将下载信息传给进度条,对进度条进行更新
  160. Message message = Message.obtain();
  161. message.what = 1;
  162. message.obj = urlstr;
  163. message.arg1 = length;
  164. mHandler.sendMessage(message);
  165. if (state == PAUSE) {
  166. return;
  167. }
  168. }
  169. } catch (Exception e) {
  170. e.printStackTrace();
  171. } finally {
  172. try {
  173. is.close();
  174. randomAccessFile.close();
  175. connection.disconnect();
  176. dao.closeDb();
  177. } catch (Exception e) {
  178. e.printStackTrace();
  179. }
  180. }
  181. }
  182. }
  183. // 删除数据库中urlstr对应的下载器信息
  184. public void delete(String urlstr) {
  185. dao.delete(urlstr);
  186. }
  187. // 设置暂停
  188. public void pause() {
  189. state = PAUSE;
  190. }
  191. // 重置下载状态
  192. public void reset() {
  193. state = INIT;
  194. }
  195. }

复制代码

在这边下载器类的定义中,我们用到了许多关于进行数据库操作的方法,这里我定义了一个数据库工具类,来提供这些方法,代码如下:
Dao:

  1. package com.icss.dao;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.crypto.spec.DESKeySpec;
  5. import com.icss.DBHelper.DBHelper;
  6. import com.icss.entity.DownloadInfo;
  7. import android.content.Context;
  8. import android.database.Cursor;
  9. import android.database.sqlite.SQLiteDatabase;
  10. /**
  11. *
  12. * 一个业务类
  13. */
  14. public class Dao {
  15. private DBHelper dbHelper;
  16. public Dao(Context context) {
  17. dbHelper = new DBHelper(context);
  18. }
  19. /**
  20. * 查看数据库中是否有数据
  21. */
  22. public boolean isHasInfors(String urlstr) {
  23. SQLiteDatabase database = dbHelper.getReadableDatabase();
  24. String sql = "select count(*)  from download_info where url=?";
  25. Cursor cursor = database.rawQuery(sql, new String[] { urlstr });
  26. cursor.moveToFirst();
  27. int count = cursor.getInt(0);
  28. cursor.close();
  29. return count == 0;
  30. }
  31. /**
  32. * 保存 下载的具体信息
  33. */
  34. public void saveInfos(List<DownloadInfo> infos) {
  35. SQLiteDatabase database = dbHelper.getWritableDatabase();
  36. for (DownloadInfo info : infos) {
  37. String sql = "insert into download_info(thread_id,start_pos, end_pos,compelete_size,url) values (?,?,?,?,?)";
  38. Object[] bindArgs = { info.getThreadId(), info.getStartPos(),
  39. info.getEndPos(), info.getCompeleteSize(), info.getUrl() };
  40. database.execSQL(sql, bindArgs);
  41. }
  42. }
  43. /**
  44. * 得到下载具体信息
  45. */
  46. public List<DownloadInfo> getInfos(String urlstr) {
  47. List<DownloadInfo> list = new ArrayList<DownloadInfo>();
  48. SQLiteDatabase database = dbHelper.getReadableDatabase();
  49. String sql = "select thread_id, start_pos, end_pos,compelete_size,url from download_info where url=?";
  50. Cursor cursor = database.rawQuery(sql, new String[] { urlstr });
  51. while (cursor.moveToNext()) {
  52. DownloadInfo info = new DownloadInfo(cursor.getInt(0),
  53. cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),
  54. cursor.getString(4));
  55. list.add(info);
  56. }
  57. cursor.close();
  58. return list;
  59. }
  60. /**
  61. * 更新数据库中的下载信息
  62. */
  63. public void updataInfos(int threadId, int compeleteSize, String urlstr) {
  64. SQLiteDatabase database = dbHelper.getReadableDatabase();
  65. String sql = "update download_info set compelete_size=? where thread_id=? and url=?";
  66. Object[] bindArgs = { compeleteSize, threadId, urlstr };
  67. database.execSQL(sql, bindArgs);
  68. }
  69. /**
  70. * 关闭数据库
  71. */
  72. public void closeDb() {
  73. dbHelper.close();
  74. }
  75. /**
  76. * 下载完成后删除数据库中的数据
  77. */
  78. public void delete(String url) {
  79. SQLiteDatabase database = dbHelper.getReadableDatabase();
  80. database.delete("download_info", "url=?", new String[] { url });
  81. database.close();
  82. }
  83. }

复制代码

下面的是程序的主程序,其他的不说了,直接上代码:

  1. package com.icss;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import android.app.ListActivity;
  7. import android.os.Bundle;
  8. import android.os.Handler;
  9. import android.os.Message;
  10. import android.view.View;
  11. import android.widget.LinearLayout;
  12. import android.widget.LinearLayout.LayoutParams;
  13. import android.widget.ProgressBar;
  14. import android.widget.SimpleAdapter;
  15. import android.widget.TextView;
  16. import android.widget.Toast;
  17. import com.icss.entity.LoadInfo;
  18. import com.icss.service.Downloader;
  19. public class MainActivity extends ListActivity {
  20. // 固定下载的资源路径,这里可以设置网络上的地址
  21. private static final String URL = "http://10.0.0.80:8080/xiangce/";
  22. // 固定存放下载的音乐的路径:SD卡目录下
  23. private static final String SD_PATH = "/mnt/sdcard/";
  24. // 存放各个下载器
  25. private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();
  26. // 存放与下载器对应的进度条
  27. private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();
  28. /**
  29. * 31 * 利用消息处理机制适时更新进度条 32
  30. */
  31. private Handler mHandler = new Handler() {
  32. public void handleMessage(Message msg) {
  33. if (msg.what == 1) {
  34. String url = (String) msg.obj;
  35. int length = msg.arg1;
  36. ProgressBar bar = ProgressBars.get(url);
  37. if (bar != null) {
  38. // 设置进度条按读取的length长度更新
  39. bar.incrementProgressBy(length);
  40. if (bar.getProgress() == bar.getMax()) {
  41. Toast.makeText(MainActivity.this, "下载完成!", 0).show();
  42. // 下载完成后清除进度条并将map中的数据清空
  43. LinearLayout layout = (LinearLayout) bar.getParent();
  44. layout.removeView(bar);
  45. ProgressBars.remove(url);
  46. downloaders.get(url).delete(url);
  47. downloaders.get(url).reset();
  48. downloaders.remove(url);
  49. }
  50. }
  51. }
  52. }
  53. };
  54. @Override
  55. public void onCreate(Bundle savedInstanceState) {
  56. super.onCreate(savedInstanceState);
  57. setContentView(R.layout.main);
  58. showListView();
  59. }
  60. // 显示listView,这里可以随便添加音乐
  61. private void showListView() {
  62. List<Map<String, String>> data = new ArrayList<Map<String, String>>();
  63. Map<String, String> map = new HashMap<String, String>();
  64. map.put("name", "mm.mp3");
  65. data.add(map);
  66. map = new HashMap<String, String>();
  67. map.put("name", "pp.mp3");
  68. data.add(map);
  69. map = new HashMap<String, String>();
  70. map.put("name", "tt.mp3");
  71. data.add(map);
  72. map = new HashMap<String, String>();
  73. map.put("name", "You.mp3");
  74. data.add(map);
  75. SimpleAdapter adapter = new SimpleAdapter(this, data,
  76. R.layout.list_item, new String[] { "name" },
  77. new int[] { R.id.tv_resouce_name });
  78. setListAdapter(adapter);
  79. }
  80. /**
  81. * 83 * 响应开始下载按钮的点击事件 84
  82. */
  83. public void startDownload(View v) {
  84. // 得到textView的内容
  85. LinearLayout layout = (LinearLayout) v.getParent();
  86. String musicName = ((TextView) layout
  87. .findViewById(R.id.tv_resouce_name)).getText().toString();
  88. String urlstr = URL + musicName;
  89. String localfile = SD_PATH + musicName;
  90. // 设置下载线程数为4,这里是我为了方便随便固定的
  91. int threadcount = 4;
  92. // 初始化一个downloader下载器
  93. Downloader downloader = downloaders.get(urlstr);
  94. if (downloader == null) {
  95. downloader = new Downloader(urlstr, localfile, threadcount, this,
  96. mHandler);
  97. downloaders.put(urlstr, downloader);
  98. }
  99. if (downloader.isdownloading())
  100. return;
  101. // 得到下载信息类的个数组成集合
  102. LoadInfo loadInfo = downloader.getDownloaderInfors();
  103. // 显示进度条
  104. showProgress(loadInfo, urlstr, v);
  105. // 调用方法开始下载
  106. downloader.download();
  107. }
  108. /**
  109. * 显示进度条
  110. */
  111. private void showProgress(LoadInfo loadInfo, String url, View v) {
  112. ProgressBar bar = ProgressBars.get(url);
  113. if (bar == null) {
  114. bar = new ProgressBar(this, null,
  115. android.R.attr.progressBarStyleHorizontal);
  116. bar.setMax(loadInfo.getFileSize());
  117. bar.setProgress(loadInfo.getComplete());
  118. System.out.println(loadInfo.getFileSize()+"--"+loadInfo.getComplete());
  119. ProgressBars.put(url, bar);
  120. LinearLayout.LayoutParams params = new LayoutParams(
  121. LayoutParams.FILL_PARENT, 5);
  122. ((LinearLayout) ((LinearLayout) v.getParent()).getParent())
  123. .addView(bar, params);
  124. }
  125. }
  126. /**
  127. * 响应暂停下载按钮的点击事件
  128. */
  129. public void pauseDownload(View v) {
  130. LinearLayout layout = (LinearLayout) v.getParent();
  131. String musicName = ((TextView) layout
  132. .findViewById(R.id.tv_resouce_name)).getText().toString();
  133. String urlstr = URL + musicName;
  134. downloaders.get(urlstr).pause();
  135. }
  136. }

复制代码

最后我们需要在android Manifest.xml中添加这两个权限一个是访问internet的权限,另一个是写外存的权限。

  1. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

复制代码

最后运行的效果图:

万事俱备只欠东风啦!哈哈,我需要在我的web工程里放几个音乐文件。

下载后得到的文件可在sdcard下面找到!

上一篇:实现android支持多线程断点续传下载器功能


下一篇:SQL日期格式化应用大全