今天跟大家一起分享下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體驗上一定記住要使用非同步完成,既然大致思路已經清楚,下面我們開始分析程式:
依賴:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin需要新增的外掛
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.bwie.duoloadding"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
//對greendao的設定
greendao {
schemaVersion 1
daoPackage 'com.bwie.yue2'//設定DaoMaster、DaoSession、Dao包名
targetGenDir 'src/main/java'//設定DaoMaster、DaoSession、Dao目錄即在什麼目錄下生成
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'org.greenrobot:greendao:3.2.0' // add library 需要新增的依賴新增
}
許可權
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.bwie.duoloadding">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:name="com.bwie.yue2.MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
User類:
-
@Entity//表示這個實體類一會會在資料庫中生成對應的表
public class User {
@Id
private Long id;
private Integer thread_id;
private Integer start_pos;
private Integer end_pos;
private Integer compelete_size;
private String url;
-
通過builder-》make module 'module名'生成Usedao,DaoMaster,daosession
資料庫操作要藉助單例和同步,來保證執行緒的執行順序,以免多個執行緒爭相搶用sqlite資源導致異常出現
-
package cn.demo.Dao;
-
-
import java.util.ArrayList;
-
import java.util.List;
-
-
import android.content.Context;
-
import android.database.Cursor;
-
import android.database.sqlite.SQLiteDatabase;
-
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 synchronized boolean isHasInfors(String urlstr) {
int count = -1;
Cursor cursor = null;
try {
List<User> list1 = MyApplication.userDao.queryBuilder().where(UserDao.Properties.Url.eq(urlstr)).list();
count = list1.size();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != cursor) {
cursor.close();
}
}
return count == 0;
}
/**
* 儲存 下載的具體資訊
*/
public synchronized void saveInfos(List<DownloadInfo> infos) {
try {
for (DownloadInfo info : infos) {
User user = new User(null, info.getThreadId(), info.getStartPos(), info.getEndPos(), info.getCompeleteSize(), info.getUrl());
MyApplication.userDao.insert(user);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 得到下載具體資訊
*/
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=?";
List<User> list1 = MyApplication.userDao.queryBuilder().where(UserDao.Properties.Url.eq(urlstr))/*.build()*/.list();
for (User user : list1) {
DownloadInfo infoss = new DownloadInfo(
user.getThread_id(), user.getStart_pos(), user.getEnd_pos(),
user.getCompelete_size(), user.getUrl());
list.add(infoss);
}
return list;
}
/**
* 更新資料庫中的下載資訊
*/
public synchronized void updataInfos(int threadId, int compeleteSize, String urlstr) {
User user = MyApplication.userDao.queryBuilder()
.where(UserDao.Properties.Thread_id.eq(threadId), UserDao.Properties.Url.eq(urlstr)).build().unique();
user.setCompelete_size(compeleteSize);
MyApplication.userDao.update(user);
}
/**
* 下載完成後刪除資料庫中的資料
*/
public synchronized void delete(String url) {
MyApplication.userDao.deleteAll();
}
-
單例模式
package com.bwie.yue2;
import android.app.Application;
/**
* Created by T_baby on 17/11/22.
*/
public class MyApplication extends Application {
public static UserDao userDao;
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "lenvess.db", null);
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
DaoSession daoSession = daoMaster.newSession();
userDao = daoSession.getUserDao();
}
}
介面卡:
-
package cn.demo.download;
-
-
import java.util.List;
-
import java.util.Map;
-
-
import android.content.Context;
-
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) {
-
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.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的一些工作
-
package cn.demo.download;
-
-
import java.util.ArrayList;
-
import java.util.HashMap;
-
import java.util.List;
-
import java.util.Map;
-
-
import android.app.ListActivity;
-
import android.os.AsyncTask;
-
import android.os.Bundle;
-
import android.os.Handler;
-
import android.os.Message;
-
import android.view.View;
-
import android.widget.Button;
-
import android.widget.LinearLayout;
-
import android.widget.LinearLayout.LayoutParams;
-
import android.widget.ProgressBar;
-
import android.widget.TextView;
-
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/";
-
-
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) {
-
-
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();
-
-
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.main);
-
showListView();
-
}
-
-
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);
-
-
}
-
-
-
-
public void startDownload(View v) {
-
-
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;
-
-
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 = 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 LayoutParams(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 = URL + 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);
-
}
-
}
這是一個資訊的實體,記錄了一些字典資訊,可以認為是一個簡單bean物件
-
package cn.demo.entity;
-
-
-
-
public class DownloadInfo {
-
private int threadId;
-
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 +"]";
-
}
-
}
-
package cn.demo.entity;
-
-
-
-
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 + "]";
-
}
-
}
這是一個核心類,專門用來處理下載的
-
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 java.util.ArrayList;
-
import java.util.List;
-
-
import android.content.Context;
-
import android.os.AsyncTask;
-
import android.os.Handler;
-
import android.os.Message;
-
import android.util.Log;
-
import cn.demo.Dao.Dao;
-
import cn.demo.entity.DownloadInfo;
-
import cn.demo.entity.LoadInfo;
-
-
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;
-
}
-
-
-
-
-
-
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);
-
-
Dao.getInstance(context).saveInfos(infos);
-
-
LoadInfo loadInfo = new LoadInfo(fileSize, 0, urlstr);
-
return loadInfo;
-
} else {
-
-
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;
-
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");
-
-
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();
-
}
-
}
-
}
-
-
public void delete(String urlstr) {
-
Dao.getInstance(context).delete(urlstr);
-
}
-
-
public void pause() {
-
state = PAUSE;
-
}
-
-
public void reset() {
-
state = INIT;
-
}
-
}
以下是些xml檔案
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>
main佈局
-
<?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>
-
<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>
執行效果如下
原始碼下載地址
http://blog.csdn.net/shimiso/article/details/49450551
android 多執行緒斷點續傳下載 四-模仿下載助手
轉載請標明出處 http://blog.csdn.net/shimiso