今天跟大家一起分享下android開發中比較難的一個環節,可能很多人看到這個标題就會感覺頭很大,的确如果沒有良好的編碼能力和邏輯思維,這塊是很難搞明白的,前面2次總結中已經為大家分享過有關技術的一些基本要領,我們先一起簡單回顧下它的基本原理。
http://blog.csdn.net/shimiso/article/details/6763664 android 多線程斷點續傳下載下傳 一
http://blog.csdn.net/shimiso/article/details/6763986 android 多線程斷點續傳下載下傳 二
什麼是多線程下載下傳?
多線程下載下傳其實就是迅雷,bt一些下載下傳原理,通過多個線程同時和伺服器連接配接,那麼你就可以榨取到較高的帶寬了,大緻做法是将檔案切割成n塊,每塊交給單獨一個線程去下載下傳,各自下載下傳完成後将檔案塊組合成一個檔案,程式上要完成做切割群組裝的小算法
什麼是斷點續傳?
斷點續傳,就是當我們下載下傳未結束時候,退出儲存下載下傳進度,當下次打開繼續下載下傳的時接着上次的進度繼續下載下傳,不用每次下載下傳都重新開始,那麼有關斷點續傳的原理和實作手段,可參考我以前的一篇總結http://blog.csdn.net/shimiso/article/details/5956314 裡面詳細講解http協定斷點續傳的原理,務必要看懂,否則你無法真正了解本節代碼
怎麼完成多線程斷點續傳?
将兩者合二為一需要程式記住每個檔案塊的下載下傳進度,并儲存入庫,當下載下傳程式啟動時候你需要判斷程式是否已經下載下傳過該檔案,并取出各個檔案塊的儲存記錄,換算出下載下傳進度繼續下載下傳,在這裡你需要掌握java多線程的基本知識,handler的使用,以及集合,算法,檔案操作等基本技能,同時還要解決sqlite資料庫的同步問題,因為它是不太怎麼支援多線程操作的,控制不好經常會出現庫被鎖定的異常,同時在android2.3以後就不能activity中直接操作http,否則你将收到系統送上的networkonmainthreadexception異常,在ui體驗上一定記住要使用異步完成,既然大緻思路已經清楚,下面我們開始分析程式:
[java] view
plaincopy
package cn.demo.dbhelper;
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)");
public void onupgrade(sqlitedatabase db, int oldversion, int newversion) {
}
資料庫操作要借助單例和同步,來保證線程的執行順序,以免多個線程争相搶用sqlite資源導緻異常出現
package cn.demo.dao;
import java.util.arraylist;
import java.util.list;
import android.content.context;
import android.database.cursor;
import cn.demo.dbhelper.dbhelper;
import cn.demo.entity.downloadinfo;
/**
*
* 一個業務類
*/
public class dao {
private static dao dao=null;
private context context;
private dao(context context) {
this.context=context;
}
public static dao getinstance(context context){
if(dao==null){
dao=new dao(context);
}
return dao;
public sqlitedatabase getconnection() {
sqlitedatabase sqlitedatabase = null;
try {
sqlitedatabase= new dbhelper(context).getreadabledatabase();
} catch (exception e) {
return sqlitedatabase;
/**
* 檢視資料庫中是否有資料
*/
public synchronized boolean ishasinfors(string urlstr) {
sqlitedatabase database = getconnection();
int count = -1;
cursor cursor = null;
try {
string sql = "select count(*) from download_info where url=?";
cursor = database.rawquery(sql, new string[] { urlstr });
if (cursor.movetofirst()) {
count = cursor.getint(0);
}
} catch (exception e) {
e.printstacktrace();
} finally {
if (null != database) {
database.close();
}
if (null != cursor) {
cursor.close();
return count == 0;
* 儲存 下載下傳的具體資訊
public synchronized void saveinfos(list<downloadinfo> infos) {
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 synchronized list<downloadinfo> getinfos(string urlstr) {
list<downloadinfo> list = new arraylist<downloadinfo>();
string sql = "select thread_id, start_pos, end_pos,compelete_size,url from download_info where url=?";
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);
return list;
* 更新資料庫中的下載下傳資訊
public synchronized void updatainfos(int threadid, int compeletesize, string urlstr) {
string sql = "update download_info set compelete_size=? where thread_id=? and url=?";
object[] bindargs = { compeletesize, threadid, urlstr };
database.execsql(sql, bindargs);
* 下載下傳完成後删除資料庫中的資料
public synchronized void delete(string url) {
database.delete("download_info", "url=?", new string[] { url });
}
package cn.demo.download;
import java.util.map;
import android.view.layoutinflater;
import android.view.view;
import android.view.view.onclicklistener;
import android.view.viewgroup;
import android.widget.baseadapter;
import android.widget.button;
import android.widget.textview;
public class downloadadapter extends baseadapter{
private layoutinflater minflater;
private list<map<string, string>> data;
private context context;
private onclicklistener click;
public downloadadapter(context context,list<map<string, string>> data) {
minflater = layoutinflater.from(context);
this.data=data;
public void refresh(list<map<string, string>> data) {
this.notifydatasetchanged();
public void setonclick(onclicklistener click) {
this.click=click;
@override
public int getcount() {
return data.size();
public object getitem(int position) {
return data.get(position);
public long getitemid(int position) {
return position;
public view getview(final int position, view convertview, viewgroup parent) {
final map<string, string> bean=data.get(position);
viewholder holder = null;
if (convertview == null) {
convertview = minflater.inflate(r.layout.list_item, null);
holder = new viewholder();
holder.resoucename=(textview) convertview.findviewbyid(r.id.tv_resouce_name);
holder.startdownload=(button) convertview.findviewbyid(r.id.btn_start);
holder.pausedownload=(button) convertview.findviewbyid(r.id.btn_pause);
convertview.settag(holder);
} else {
holder = (viewholder) convertview.gettag();
}
holder.resoucename.settext(bean.get("name"));
return convertview;
public onclicklistener getclick() {
return click;
public void setclick(onclicklistener click) {
this.click = click;
private class viewholder {
public textview resoucename;
public button startdownload;
public button pausedownload;
注意子線程不要影響主ui線程,靈活運用task和handler,各取所長,保證使用者體驗,handler通常在主線程中有利于專門負責處理ui的一些工作
import java.util.arraylist;
import java.util.hashmap;
import android.app.listactivity;
import android.os.asynctask;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.widget.linearlayout;
import android.widget.linearlayout.layoutparams;
import android.widget.progressbar;
import android.widget.toast;
import cn.demo.entity.loadinfo;
import cn.demo.service.downloader;
public class mainactivity extends listactivity {
// 固定下載下傳的資源路徑,這裡可以設定網絡上的位址
private static final string url = "http://download.haozip.com/";
// 固定存放下載下傳的音樂的路徑: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()) {
linearlayout layout = (linearlayout) bar.getparent();
textview resoucename=(textview)layout.findviewbyid(r.id.tv_resouce_name);
toast.maketext(mainactivity.this, "["+resoucename.gettext()+"]下載下傳完成!", toast.length_short).show();
// 下載下傳完成後清除進度條并将map中的資料清空
layout.removeview(bar);
progressbars.remove(url);
downloaders.get(url).delete(url);
downloaders.get(url).reset();
downloaders.remove(url);
button btn_start=(button)layout.findviewbyid(r.id.btn_start);
button btn_pause=(button)layout.findviewbyid(r.id.btn_pause);
btn_pause.setvisibility(view.gone);
btn_start.setvisibility(view.gone);
}
}
}
}
};
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
showlistview();
// 顯示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", "haozip_v3.1.exe");
data.add(map);
map = new hashmap<string, string>();
map.put("name", "haozip_v3.1_hj.exe");
map.put("name", "haozip_v2.8_x64_tiny.exe");
map.put("name", "haozip_v2.8_tiny.exe");
downloadadapter adapter=new downloadadapter(this,data);
setlistadapter(adapter);
* 響應開始下載下傳按鈕的點選事件
public void startdownload(view v) {
// 得到textview的内容
linearlayout layout = (linearlayout) v.getparent();
string resoucename = ((textview) layout.findviewbyid(r.id.tv_resouce_name)).gettext().tostring();
string urlstr = url + resoucename;
string localfile = sd_path + resoucename;
//設定下載下傳線程數為4,這裡是我為了友善随便固定的
string threadcount = "4";
downloadtask downloadtask=new downloadtask(v);
downloadtask.execute(urlstr,localfile,threadcount);
class downloadtask extends asynctask<string, integer, loadinfo>{
downloader downloader=null;
view v=null;
string urlstr=null;
public downloadtask(final view v){
this.v=v;
}
@override
protected void onpreexecute() {
button btn_start=(button)((view)v.getparent()).findviewbyid(r.id.btn_start);
button btn_pause=(button)((view)v.getparent()).findviewbyid(r.id.btn_pause);
btn_start.setvisibility(view.gone);
btn_pause.setvisibility(view.visible);
protected loadinfo doinbackground(string... params) {
urlstr=params[0];
string localfile=params[1];
int threadcount=integer.parseint(params[2]);
// 初始化一個downloader下載下傳器
downloader = downloaders.get(urlstr);
if (downloader == null) {
downloader = new downloader(urlstr, localfile, threadcount, mainactivity.this, mhandler);
downloaders.put(urlstr, downloader);
if (downloader.isdownloading())
return null;
// 得到下載下傳資訊類的個數組成集合
return downloader.getdownloaderinfors();
protected void onpostexecute(loadinfo loadinfo) {
if(loadinfo!=null){
// 顯示進度條
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) {
downloaders.get(urlstr).pause();
button btn_start=(button)((view)v.getparent()).findviewbyid(r.id.btn_start);
button btn_pause=(button)((view)v.getparent()).findviewbyid(r.id.btn_pause);
btn_pause.setvisibility(view.gone);
btn_start.setvisibility(view.visible);
這是一個資訊的實體,記錄了一些字典資訊,可以認為是一個簡單bean對象
package cn.demo.entity;
/**
*建立一個下載下傳資訊的實體類
*/
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) {
public int getstartpos() {
return startpos;
public void setstartpos(int startpos) {
public int getendpos() {
return endpos;
public void setendpos(int endpos) {
public int getcompeletesize() {
return compeletesize;
public void setcompeletesize(int compeletesize) {
public string tostring() {
return "downloadinfo [threadid=" + threadid
+ ", startpos=" + startpos + ", endpos=" + endpos
+ ", compeletesize=" + compeletesize +"]";
*自定義的一個記載下載下傳器詳細資訊的類
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) {
public int getcomplete() {
return complete;
public void setcomplete(int complete) {
public string geturlstring() {
return urlstring;
public void seturlstring(string urlstring) {
return "loadinfo [filesize=" + filesize + ", complete=" + complete
+ ", urlstring=" + urlstring + "]";
這是一個核心類,專門用來處理下載下傳的
package cn.demo.service;
import java.io.file;
import java.io.inputstream;
import java.io.randomaccessfile;
import java.net.httpurlconnection;
import java.net.url;
import android.util.log;
import cn.demo.dao.dao;
public class downloader {
private string urlstr;// 下載下傳的位址
private string localfile;// 儲存路徑
private int threadcount;// 線程數
private handler mhandler;// 消息處理器
private int filesize;// 所要下載下傳的檔案的大小
private context context;
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;
this.context = 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.getinstance(context).saveinfos(infos);
//建立一個loadinfo對象記載下載下傳器的具體資訊
loadinfo loadinfo = new loadinfo(filesize, 0, urlstr);
return loadinfo;
} else {
//得到資料庫中已有的urlstr的下載下傳器的具體資訊
infos = dao.getinstance(context).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.getinstance(context).ishasinfors(urlstr);
* 利用線程開始下載下傳資料
public void download() {
if (infos != null) {
if (state == downloading)
return;
state = downloading;
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);
// 将要下載下傳的檔案寫到儲存在儲存路徑下的檔案中
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.getinstance(context).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();
}
//删除資料庫中urlstr對應的下載下傳器資訊
public void delete(string urlstr) {
dao.getinstance(context).delete(urlstr);
//設定暫停
public void pause() {
state = pause;
//重置下載下傳狀态
public void reset() {
state = init;
以下是些xml檔案
[html] view
<?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="wrap_content">
<linearlayout
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_marginbottom="5dip">
<textview
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/tv_resouce_name"/>
<button
android:text="下載下傳"
android:id="@+id/btn_start"
android:onclick="startdownload"/>
android:text="暫停"
android:visibility="gone"
android:id="@+id/btn_pause"
android:onclick="pausedownload"/>
</linearlayout>
</linearlayout>
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>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.demo.download"
android:versioncode="1"
android:versionname="1.0">
<uses-sdk android:minsdkversion="8" android:targetsdkversion="8" />
<uses-permission android:name="android.permission.internet"/>
<uses-permission android:name="android.permission.write_external_storage"/>
<application android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
android:theme="@style/apptheme">
<activity
android:name=".mainactivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.main" />
<category android:name="android.intent.category.launcher" />
</intent-filter>
</activity>
</application>
</manifest>
運作效果如下

源碼下載下傳位址