Android 多執行緒斷點下載demo實現
先來一張效果圖:
主要實現思路:
每一個下載都是通過RandomAccessFile對下載資源的總長進行切割之後,根據我們設定的執行緒多少進行計算之後開啟多執行緒下載的。而每一個任務都是一個AsyncTask。資料的儲存都是通過SQL來進行,保證整個下載任務的斷續不受影響。
一:資料庫操作的工具類,根據資料庫設計而生成的bean類:
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) { } }
資料庫操作類,包括檢視,儲存,更新,獲取,以及下載完畢之後的刪除操作。
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) { SQLiteDatabase database = getConnection(); try { 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); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != database) { database.close(); } } } /** * 得到下載具體資訊 */ public synchronized List<DownloadInfo> getInfos(String urlstr) { List<DownloadInfo> list = new ArrayList<>(); SQLiteDatabase database = getConnection(); Cursor cursor = null; try { String sql = "select thread_id, start_pos, end_pos,compelete_size,url from download_info where url=?"; 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); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != database) { database.close(); } if (null != cursor) { cursor.close(); } } return list; } /** * 更新資料庫中的下載資訊 */ public synchronized void updataInfos(int threadId, int compeleteSize, String urlstr) { SQLiteDatabase database = getConnection(); try { String sql = "update download_info set compelete_size=? where thread_id=? and url=?"; Object[] bindArgs = { compeleteSize, threadId, urlstr }; database.execSQL(sql, bindArgs); } catch (Exception e) { e.printStackTrace(); } finally { if (null != database) { database.close(); } } } /** * 下載完成後刪除資料庫中的資料 */ public synchronized void delete(String url) { SQLiteDatabase database = getConnection(); try { database.delete("download_info", "url=?", new String[] { url }); } catch (Exception e) { e.printStackTrace(); } finally { if (null != database) { database.close(); } } } }
根據資料庫設計的欄位自己編寫的bean類:
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 +"]"; } }
從DownLoadInfo中獲取到的幾個資料要返回給activity進行進度的更新的實體類
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類,所有下載邏輯在這裡進行,並連線資料庫工具類進行操作。
首先就是構造,我們需要獲取到的資料,肯定要包括自己設計的資料庫裡邊的欄位的資料,其次肯定還要知道多執行緒的指定數,
最後就是需要一個在activity中定義好的handler來進行進度的傳遞。
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;
}
那麼下載的狀態也是必須要提前準備好的
private static final int INIT = 1;//定義三種下載的狀態:初始化狀態,正在下載狀態,暫停狀態
private static final int DOWNLOADING = 2;
private static final int PAUSE = 3;
/**
*判斷是否正在下載
*/
public boolean isdownloading() {
return state == DOWNLOADING;
}
//刪除資料庫中urlstr對應的下載器資訊
public void delete(String urlstr) {
Dao.getInstance(context).delete(urlstr);
}
//設定暫停
public void pause() {
state = PAUSE;
}
//重置下載狀態
public void reset() {
state = INIT;
}
開始進入整個下載的邏輯
首先是判斷是否是第一次下載:
/**
* 判斷是否是第一次 下載
*/
private boolean isFirst(String urlstr) {
return Dao.getInstance(context).isHasInfors(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();
}
}
總長度獲取到之後,我們就需要通過執行緒的數量來進行計算每條執行緒開始的斷點的位置,並且將每條執行緒的任務用bean類進行儲存,並存儲在list中,然後進行資料庫的save。
int range = fileSize / threadcount;
infos = new ArrayList<>();
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);
那麼如果不是第一次下載該資源,就需要先從資料庫中獲取到下載的資訊。因為是斷點下載,僅需要通過for迴圈計算出已下載的資源的總長度
//得到資料庫中已有的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;
}
而因為我們要在activity中更新progressBar的進度條,所以我們需要將completeSize、filesize給傳遞到activity中重新整理ui,而為了區分開每個prgressBar對應的下載任務,我們就需要一個key來進行區分,每個資源的url肯定是不同的,也是最適合這個工作的,所以就可以得到以下的程式碼: /**
* 得到downloader裡的資訊
* 首先進行判斷是否是第一次下載,如果是第一次就要進行初始化,並將下載器的資訊儲存到資料庫中
* 如果不是第一次下載,那就要從資料庫中讀出之前下載的資訊(起始位置,結束為止,檔案大小等),並將下載資訊返回給下載器
*/
public LoadInfo getDownloaderInfors() {
if (isFirst(urlstr)) {
Log.v("TAG", "isFirst");
init();
int range = fileSize / threadcount;
infos = new ArrayList<>();
for (int i = 0; i < threadcount - 1; i++) {
DownloadInfo info = new DownloadInfo(i, i * range, (i + 1)* range - 1, 0, urlstr);//因為是第一次,所以completeSize為0;
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();//因為已經下載過,所以需要計算出已下載的completeSize進行介面更新。
size += info.getEndPos() - info.getStartPos() + 1;
}
return new LoadInfo(size, compeleteSize, urlstr);
}
}
在每次下載任務之前需要先去獲取一下getDownloaderInfors()下載的資訊,注意這個資訊因為包含資料庫操作,且init中需要聯網獲取資源總長,所以需要在子執行緒中進行。
接下來開始進行具體的下載工作:
/**
* 利用執行緒開始下載資料
*/
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();
}
}
}
斷點下載就需要將我們前面準備工作中獲取到的DownLoadInfo的集合進行遍歷,將每一個執行緒應該從哪兒到哪兒的下載任務區分好,整個執行緒的邏輯如下:
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();
}finally {
try {
if (connection!=null)connection.disconnect();
if (randomAccessFile!=null)randomAccessFile.close();
if (is!=null)is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
計算每個執行緒起始的下載位置,通過randomAccessFile.seek(startPos + compeleteSize)來快進到開始位置。然後進行while迴圈下載,不斷的更新資料庫(這一塊的資料庫操作很頻繁,還在想怎麼優化,但是感覺怎麼優化都不太合適),並通過handler將完成度傳遞給activity進行介面更新。並且判斷當前狀態是否是已暫停,已暫停就直接跳出迴圈停止任務。最後記得關閉流。
這樣整個下載工具類就結束了,接下來就是activity中對該類的呼叫以及介面的更新了、
三:Activity中的程式碼邏輯
首先是準備工作:
// 固定下載的資源路徑,這裡可以設定網路上的地址
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>();
這裡將downloader和progressbar儲存在map中,並且將下載的url作為key,這樣就保證了資料的唯一。
資料的展示是使用的listview和adapter進行操作:
顯示資料的準備:
// 顯示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");
data.add(map);
map = new HashMap<String, String>();
map.put("name", "haozip_v2.8_x64_tiny.exe");
data.add(map);
map = new HashMap<String, String>();
map.put("name", "haozip_v2.8_tiny.exe");
data.add(map);
DownLoadAdapter adapter=new DownLoadAdapter(this,data);
setListAdapter(adapter);
}
adapter中也就是顯示一下資源名,這裡就不貼上了。
item中的佈局檔案:
<?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_width="fill_parent"
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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="下載"
android:id="@+id/btn_start"
android:onClick="startDownload"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="暫停"
android:visibility="gone"
android:id="@+id/btn_pause"
android:onClick="pauseDownload"/>
</LinearLayout>
</LinearLayout>
直接給每個item的button設定onclick事件,在activity中進行操作。(progressBar是在程式碼中new出來的,更方便控制)。
/**
* 響應開始下載按鈕的點選事件
*/
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);
};
點選開始按鈕之後,開啟一個AsyncTask來進行下載的邏輯。
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);
}
@Override
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();
}
@Override
protected void onPostExecute(LoadInfo loadInfo) {
if(loadInfo!=null){
// 顯示進度條
showProgress(loadInfo, urlstr, v);
// 呼叫方法開始下載
downloader.download();
}
}
};
DownloadTask需要將button這個view通過構造方法傳遞過來,在準備階段進行切換,將開始按鈕隱藏,暫停按鈕開啟(當然也可以兩個按鈕都同時存在,就不用這麼麻煩)。
在doInBackground中先進行DownLoader的初始化並且put到map中。這一步在downloader中主要是獲取到資源總長以及分段生成DownloadInfo實體類,和儲存這些實體類的list集合。最後獲取到loadInfo,在下面進行介面的更新。
在onPostExecute()中先是進行介面的更新(畢竟有可能是下載過資料的),然後開始進行分段下載。
/**
* 顯示進度條
*/
private void showProgress(LoadInfo loadInfo, String url, View v) {
ProgressBar bar = ProgressBars.get(url);
if (bar == null) {//new出一個progressBar並進行addView新增到item中
bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
bar.setMax(loadInfo.getFileSize());//根據在上一步驟中獲取到的資源總長度設定bar的最大值
bar.setProgress(loadInfo.getComplete());
ProgressBars.put(url, bar);//put到map中
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 5);
((LinearLayout) ((LinearLayout) v.getParent()).getParent()).addView(bar, params);
}
}
最後就是更新ui了,在activity中new一個handler,在Downloader初始化時傳遞過去,在下載中不斷髮送進度,在activity中獲取到並及時更新:
/**
* 利用訊息處理機制適時更新進度條
*/
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) {
// 增加指定的進度
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);
}
}
}
}
};
這裡首先要注意,因為是多執行緒下載,且傳遞的message中是每一個執行緒下載的length,不是總長度,所以這邊需要呼叫
bar.incrementProgressBy(length);
方法進行progressBar的更新,不能直接採用setProgress(length)的方法。
最後就是下載完畢之後記得UI得操作,提示使用者,以及資料的刪除。
附上activity的整體程式碼以及adapter的程式碼:
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) {
this.context=context;
mInflater = LayoutInflater.from(context);
this.data=data;
}
public void refresh(List<Map<String, String>> data) {
this.data=data;
this.notifyDataSetChanged();
}
public void setOnclick(OnClickListener click) {
this.click=click;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
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.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;
}
}
public class MainActivity extends AppCompatActivity {
private String[] urls={"http://jzvd.nathen.cn/c494b340ff704015bb6682ffde3cd302/64929c369124497593205a4190d7d128-5287d2089db37e62345123a1be272f8b.mp4",
"http://jzvd.nathen.cn/63f3f73712544394be981d9e4f56b612/69c5767bb9e54156b5b60a1b6edeb3b5-5287d2089db37e62345123a1be272f8b.mp4",
"http://jzvd.nathen.cn/b201be3093814908bf987320361c5a73/2f6d913ea25941ffa78cc53a59025383-5287d2089db37e62345123a1be272f8b.mp4",
"http://jzvd.nathen.cn/d2438fd1c37c4618a704513ad38d68c5/68626a9d53ca421c896ac8010f172b68-5287d2089db37e62345123a1be272f8b.mp4",
"http://jzvd.nathen.cn/25a8d119cfa94b49a7a4117257d8ebd7/f733e65a22394abeab963908f3c336db-5287d2089db37e62345123a1be272f8b.mp4",
"http://jzvd.nathen.cn/7512edd1ad834d40bb5b978402274b1a/9691c7f2d7b74b5e811965350a0e5772-5287d2089db37e62345123a1be272f8b.mp4",
"http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4"
};
// 固定存放下載的音樂的路徑: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);
}
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showListView();
}
// 顯示listView,這裡可以隨便新增
private void showListView() {
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (int i=0;i<urls.length;i++){
Map<String, String> map = new HashMap<String, String>();
map.put("name", urls[i]);
data.add(map);
}
DownLoadAdapter adapter=new DownLoadAdapter(this,data);
setListAdapter(adapter);
}
private void setListAdapter(DownLoadAdapter adapter) {
ListView listView=findViewById(R.id.list);
listView.setAdapter(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 = resouceName;
String localfile = SD_PATH + resouceName.substring(resouceName.lastIndexOf("/"));
//設定下載執行緒數為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);
}
@Override
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();
}
@Override
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 LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 5);
((LinearLayout) ((LinearLayout) v.getParent()).getParent()).addView(bar, params);
}
}
/**
* 響應暫停下載按鈕的點選事件
*/
public void pauseDownload(View v) {
LinearLayout layout = (LinearLayout) v.getParent();
String resouceName = ((TextView) layout.findViewById(R.id.tv_resouce_name)).getText().toString();
String urlstr =resouceName;
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);
}
}
本專案已上傳github:點選開啟連結