android实现断点续传

代码如下:

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.app.ListActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity  {

	     // 固定下载的资源路径,这里可以设置网络上的地址
	      private static final String URL = "http://10.81.36.193:8080/";
	      // 固定存放下载的音乐的路径:SD卡目录下
	      private static final String SD_PATH = "/mnt/sdcard/";
	      // 存放各个下载器
	      private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();
	      // 存放与下载器对应的进度条
	      private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();
	      /**
	       * 利用消息处理机制适时更新进度条
	       */
	      private Handler mHandler = new Handler() {
	          public void handleMessage(Message msg) {
	              if (msg.what == 1) {
	                  String url = (String) msg.obj;
	                  int length = msg.arg1;
	                  ProgressBar bar = ProgressBars.get(url);
	                  if (bar != null) {
	                      // 设置进度条按读取的length长度更新
	                      bar.incrementProgressBy(length);
	                      if (bar.getProgress() == bar.getMax()) {
	                          Toast.makeText(MainActivity.this, "下载完成!", 0).show();
	                          // 下载完成后清除进度条并将map中的数据清空
	                          LinearLayout layout = (LinearLayout) bar.getParent();
	                          layout.removeView(bar);
	                          ProgressBars.remove(url);
	                          downloaders.get(url).delete(url);
	                          downloaders.get(url).reset();
	                          downloaders.remove(url);
	                      }
	                  }
	              }
	          }
	      };
	      @Override
	      public void onCreate(Bundle savedInstanceState) {
	          super.onCreate(savedInstanceState);
	          setContentView(R.layout.activity_main);
	          showListView();
	          StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
	  	      StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
	      }
	      // 显示listView,这里可以随便添加音乐
	      private void showListView() {
	          List<Map<String, String>> data = new ArrayList<Map<String, String>>();
	          Map<String, String> map = new HashMap<String, String>();
	          map.put("name", "mm.mp3");
	          data.add(map);
	          map = new HashMap<String, String>();
	          map.put("name", "pp.mp3");
	          data.add(map);
	          map = new HashMap<String, String>();
	          map.put("name", "tt.mp3");
	          data.add(map);
	          map = new HashMap<String, String>();
	          map.put("name", "ou.mp3");
	          data.add(map);
	          SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.list_item, new String[] { "name" },
	                  new int[] { R.id.tv_resouce_name });
	          setListAdapter(adapter);
	      }
	      /**
	       * 响应开始下载按钮的点击事件
	       */
	      public void startDownload(View v) {
	          // 得到textView的内容
	          LinearLayout layout = (LinearLayout) v.getParent();
	          String musicName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();
	          String urlstr = URL + musicName;
	          String localfile = SD_PATH + musicName;
	          //设置下载线程数为4,这里是我为了方便随便固定的
	          int threadcount = 4;
	          // 初始化一个downloader下载器
	          Downloader downloader = downloaders.get(urlstr);
	          if (downloader == null) {
	              downloader = new Downloader(urlstr, localfile, threadcount, this, mHandler);
	              downloaders.put(urlstr, downloader);
	          }
	          if (downloader.isdownloading())
	             return;
	         // 得到下载信息类的个数组成集合
	         LoadInfo loadInfo = downloader.getDownloaderInfors();
	         // 显示进度条
	         showProgress(loadInfo, urlstr, v);
	         // 调用方法开始下载
	         downloader.download();
	     }
	
	     /**
	      * 显示进度条
	      */
	     private void showProgress(LoadInfo loadInfo, String url, View v) {
	         ProgressBar bar = ProgressBars.get(url);
	         if (bar == null) {
	             bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
	             bar.setMax(loadInfo.getFileSize());
	             bar.setProgress(loadInfo.getComplete());
	             ProgressBars.put(url, bar);
	             LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 5);
	             ((LinearLayout) ((LinearLayout) v.getParent()).getParent()).addView(bar, params);
	         }
	     }
	     /**
	      * 响应暂停下载按钮的点击事件
	      */
	     public void pauseDownload(View v) {
	         LinearLayout layout = (LinearLayout) v.getParent();
	         String musicName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();
	         String urlstr = URL + musicName;
	         downloaders.get(urlstr).pause();
	     }
	 }

DBHelper:

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

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 建立一个数据库帮助类
 */
public class DBHelper extends SQLiteOpenHelper {
	// download.db-->数据库名
	public DBHelper(Context context) {
		super(context, "download.db", null, 1);
	}

	/**
	 * 在download.db数据库下创建一个download_info表存储下载信息
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("create table download_info(_id integer PRIMARY KEY AUTOINCREMENT, thread_id integer, "
				+ "start_pos integer, end_pos integer, compelete_size integer,url char)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}

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

public class DownloadInfo {
	private int threadId;// 下载器id
	private int startPos;// 开始点
	private int endPos;// 结束点
	private int compeleteSize;// 完成度
	private String url;// 下载器网络标识

	public DownloadInfo(int threadId, int startPos, int endPos,
			int compeleteSize, String url) {
		this.threadId = threadId;
		this.startPos = startPos;
		this.endPos = endPos;
		this.compeleteSize = compeleteSize;
		this.url = url;
	}

	public DownloadInfo() {
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public int getThreadId() {
		return threadId;
	}

	public void setThreadId(int threadId) {
		this.threadId = threadId;
	}

	public int getStartPos() {
		return startPos;
	}

	public void setStartPos(int startPos) {
		this.startPos = startPos;
	}

	public int getEndPos() {
		return endPos;
	}

	public void setEndPos(int endPos) {
		this.endPos = endPos;
	}

	public int getCompeleteSize() {
		return compeleteSize;
	}

	public void setCompeleteSize(int compeleteSize) {
		this.compeleteSize = compeleteSize;
	}

	@Override
	public String toString() {
		return "DownloadInfo [threadId=" + threadId + ", startPos=" + startPos
				+ ", endPos=" + endPos + ", compeleteSize=" + compeleteSize
				+ "]";
	}
}

LoadInfo:

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

public class LoadInfo {
	public int fileSize;// 文件大小
	private int complete;// 完成度
	private String urlstring;// 下载器标识

	public LoadInfo(int fileSize, int complete, String urlstring) {
		this.fileSize = fileSize;
		this.complete = complete;
		this.urlstring = urlstring;
	}

	public LoadInfo() {
	}

	public int getFileSize() {
		return fileSize;
	}

	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

	public int getComplete() {
		return complete;
	}

	public void setComplete(int complete) {
		this.complete = complete;
	}

	public String getUrlstring() {
		return urlstring;
	}

	public void setUrlstring(String urlstring) {
		this.urlstring = urlstring;
	}

	@Override
	public String toString() {
		return "LoadInfo [fileSize=" + fileSize + ", complete=" + complete
				+ ", urlstring=" + urlstring + "]";
	}
}

Downloader:

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

 public class Downloader {
     private String urlstr;// 下载的地址
     private String localfile;// 保存路径
     private int threadcount;// 线程数
     private Handler mHandler;// 消息处理器
     private Dao dao;// 工具类
     private int fileSize;// 所要下载的文件的大小
     private List<DownloadInfo> infos;// 存放下载信息类的集合
     private static final int INIT = 1;//定义三种下载的状态:初始化状态,正在下载状态,暂停状态
     private static final int DOWNLOADING = 2;
     private static final int PAUSE = 3;
     private int state = INIT;

     public Downloader(String urlstr, String localfile, int threadcount,
             Context context, Handler mHandler) {
         this.urlstr = urlstr;
         this.localfile = localfile;
         this.threadcount = threadcount;
         this.mHandler = mHandler;
         dao = new Dao(context);
     }
     /**
      *判断是否正在下载
      */
     public boolean isdownloading() {
         return state == DOWNLOADING;
     }
     /**
      * 得到downloader里的信息
      * 首先进行判断是否是第一次下载,如果是第一次就要进行初始化,并将下载器的信息保存到数据库中
      * 如果不是第一次下载,那就要从数据库中读出之前下载的信息(起始位置,结束为止,文件大小等),并将下载信息返回给下载器
      */
     public LoadInfo getDownloaderInfors() {
         if (isFirst(urlstr)) {
             Log.v("TAG", "isFirst");
             init();
             int range = fileSize / threadcount;
             infos = new ArrayList<DownloadInfo>();
             for (int i = 0; i < threadcount - 1; i++) {
                 DownloadInfo info = new DownloadInfo(i, i * range, (i + 1)* range - 1, 0, urlstr);
                 infos.add(info);
             }
             DownloadInfo info = new DownloadInfo(threadcount - 1,(threadcount - 1) * range, fileSize - 1, 0, urlstr);
             infos.add(info);
             //保存infos中的数据到数据库
             dao.saveInfos(infos);
             //创建一个LoadInfo对象记载下载器的具体信息
             LoadInfo loadInfo = new LoadInfo(fileSize, 0, urlstr);
             return loadInfo;
         } else {
             //得到数据库中已有的urlstr的下载器的具体信息
             infos = dao.getInfos(urlstr);
             Log.v("TAG", "not isFirst size=" + infos.size());
             int size = 0;
             int compeleteSize = 0;
             for (DownloadInfo info : infos) {
                 compeleteSize += info.getCompeleteSize();
                 size += info.getEndPos() - info.getStartPos() + 1;
             }
             return new LoadInfo(size, compeleteSize, urlstr);
         }
     }

     /**
      * 初始化
      */
     private void init() {
         try {
             URL url = new URL(urlstr);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setConnectTimeout(5000);
             connection.setRequestMethod("GET");
             fileSize = connection.getContentLength();

             File file = new File(localfile);
             if (!file.exists()) {
                 file.createNewFile();
             }
             // 本地访问文件
             RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
             accessFile.setLength(fileSize);
             accessFile.close();
             connection.disconnect();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }

     /**
      * 判断是否是第一次 下载
      */
     private boolean isFirst(String urlstr) {
         return dao.isHasInfors(urlstr);
     }

     /**
      * 利用线程开始下载数据
      */
     public void download() {
         if (infos != null) {
             if (state == DOWNLOADING)
                 return;
             state = DOWNLOADING;
             for (DownloadInfo info : infos) {
                 new MyThread(info.getThreadId(), info.getStartPos(),
                         info.getEndPos(), info.getCompeleteSize(),
                         info.getUrl()).start();
             }
         }
     }

     public class MyThread extends Thread {
         private int threadId;
         private int startPos;
         private int endPos;
         private int compeleteSize;
         private String urlstr;

         public MyThread(int threadId, int startPos, int endPos,
                 int compeleteSize, String urlstr) {
             this.threadId = threadId;
             this.startPos = startPos;
             this.endPos = endPos;
             this.compeleteSize = compeleteSize;
             this.urlstr = urlstr;
         }
         @Override
         public void run() {
             HttpURLConnection connection = null;
             RandomAccessFile randomAccessFile = null;
             InputStream is = null;
             try {
            	
                 URL url = new URL(urlstr);
                 connection = (HttpURLConnection) url.openConnection();
                 connection.setConnectTimeout(5000);
                 connection.setRequestMethod("GET");
                 // 设置范围,格式为Range:bytes x-y;
                 connection.setRequestProperty("Range", "bytes="+(startPos + compeleteSize) + "-" + endPos);

                 randomAccessFile = new RandomAccessFile(localfile, "rwd");
                 randomAccessFile.seek(startPos + compeleteSize);
                 Log.i("RG", "connection--->>>"+connection);
                 // 将要下载的文件写到保存在保存路径下的文件中
                 is = connection.getInputStream();
                 byte[] buffer = new byte[4096];
                 int length = -1;
                 while ((length = is.read(buffer)) != -1) {
                     randomAccessFile.write(buffer, 0, length);
                     compeleteSize += length;
                     // 更新数据库中的下载信息
                     dao.updataInfos(threadId, compeleteSize, urlstr);
                     // 用消息将下载信息传给进度条,对进度条进行更新
                     Message message = Message.obtain();
                     message.what = 1;
                     message.obj = urlstr;
                     message.arg1 = length;
                     mHandler.sendMessage(message);
                     if (state == PAUSE) {
                         return;
                     }
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             } finally {
                 try {
                     is.close();
                     randomAccessFile.close();
                     connection.disconnect();
                     dao.closeDb();
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }

         }
     }
     //删除数据库中urlstr对应的下载器信息
     public void delete(String urlstr) {
         dao.delete(urlstr);
     }
     //设置暂停
     public void pause() {
         state = PAUSE;
     }
     //重置下载状态
     public void reset() {
        state = INIT;
     }
 }

Dao:

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

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Dao {
	private DBHelper dbHelper;

	public Dao(Context context) {
		dbHelper = new DBHelper(context);
	}

	/**
	 * 查看数据库中是否有数据
	 */
	public boolean isHasInfors(String urlstr) {
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		String sql = "select count(*)  from download_info where url=?";
		Cursor cursor = database.rawQuery(sql, new String[] { urlstr });
		cursor.moveToFirst();
		int count = cursor.getInt(0);
		cursor.close();
		return count == 0;
	}

	/**
	 * 36 * 保存 下载的具体信息 37
	 */
	public void saveInfos(List<DownloadInfo> infos) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		for (DownloadInfo info : infos) {
			String sql = "insert into download_info(thread_id,start_pos, end_pos,compelete_size,url) values (?,?,?,?,?)";
			Object[] bindArgs = { info.getThreadId(), info.getStartPos(),
					info.getEndPos(), info.getCompeleteSize(), info.getUrl() };
			database.execSQL(sql, bindArgs);
		}
	}

	/**
	 * 得到下载具体信息
	 */
	public List<DownloadInfo> getInfos(String urlstr) {
		List<DownloadInfo> list = new ArrayList<DownloadInfo>();
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		String sql = "select thread_id, start_pos, end_pos,compelete_size,url from download_info where url=?";
		Cursor cursor = database.rawQuery(sql, new String[] { urlstr });
		while (cursor.moveToNext()) {
			DownloadInfo info = new DownloadInfo(cursor.getInt(0),
					cursor.getInt(1), cursor.getInt(2), cursor.getInt(3),
					cursor.getString(4));
			list.add(info);
		}
		cursor.close();
		return list;
	}

	/**
	 * 更新数据库中的下载信息
	 */
	public void updataInfos(int threadId, int compeleteSize, String urlstr) {
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		String sql = "update download_info set compelete_size=? where thread_id=? and url=?";
		Object[] bindArgs = { compeleteSize, threadId, urlstr };
		database.execSQL(sql, bindArgs);
	}

	/**
	 * 关闭数据库
	 */
	public void closeDb() {
		dbHelper.close();
	}

	/**
	 * 下载完成后删除数据库中的数据
	 */
	public void delete(String url) {
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		database.delete("download_info", "url=?", new String[] { url });
		database.close();
	}
}

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.       android:id="@+id/llRoot">  
  7.       <ListView android:id="@android:id/list"  
  8.           android:layout_width="fill_parent"  
  9.           android:layout_height="fill_parent">  
  10.      </ListView>  
  11.  </LinearLayout>  
  12.    
<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:id="@+id/llRoot">
      <ListView android:id="@android:id/list"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent">
     </ListView>
 </LinearLayout>
 

item_list.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <LinearLayout  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_marginBottom="5dip"  
  11.         android:orientation="horizontal" >  
  12.   
  13.         <TextView  
  14.             android:id="@+id/tv_resouce_name"  
  15.             android:layout_width="fill_parent"  
  16.             android:layout_height="wrap_content"  
  17.             android:layout_weight="1" />  
  18.   
  19.         <Button  
  20.             android:id="@+id/btn_start"  
  21.             android:layout_width="fill_parent"  
  22.             android:layout_height="wrap_content"  
  23.             android:layout_weight="1"  
  24.             android:onClick="startDownload"  
  25.             android:text="下载" />  
  26.   
  27.         <Button  
  28.             android:id="@+id/btn_pause"  
  29.             android:layout_width="fill_parent"  
  30.             android:layout_height="wrap_content"  
  31.             android:layout_weight="1"  
  32.             android:onClick="pauseDownload"  
  33.             android:text="暂停" />  
  34.     </LinearLayout>  
  35.   
  36. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tv_resouce_name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/btn_start"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="startDownload"
            android:text="下载" />

        <Button
            android:id="@+id/btn_pause"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="pauseDownload"
            android:text="暂停" />
    </LinearLayout>

</LinearLayout>

记得加权限:
  1. <uses-permission android:name="android.permission.INTERNET"/>  
  2.  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
<uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

还有在3.0以上的版本记得加上这句话:
  1. StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());  
  2.           StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());  
 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
	  	      StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

效果图如下:




转载地址:http://blog.youkuaiyun.com/csh159/article/details/8442970



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值