先來一張效果圖:
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: 點選打開連結