android中多線程下載實(shí)例
更新時(shí)間:2013年06月20日 15:08:59 作者:
本文以實(shí)例的方式為大家介紹下android中的多線程下載附源碼,感興趣的朋友可以學(xué)習(xí)下哈
復(fù)制代碼 代碼如下:
public class MainActivity extends Activity {
// 聲明控件
// 路徑與線程數(shù)量
private EditText et_url, et_num;
// 進(jìn)度條
public static ProgressBar pb_thread;
// 顯示進(jìn)度的操作
private TextView tv_pb;
// 線程的數(shù)量
public static int threadNum = 3;
// 每個(gè)線程負(fù)責(zé)下載的大小
public int blockSize;
public static int threadCount;// 數(shù)量
// 訪問的path
public String path;
public static boolean flag = true;
// 記錄進(jìn)度條的值
public static int pb_count = 0;
public static Handler handler;
public static final int TEXTVALUE = 1;
public static int pb_num = 0;
public static int size = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_url = (EditText) findViewById(R.id.et_path);
et_num = (EditText) findViewById(R.id.et_threadNum);
pb_thread = (ProgressBar) findViewById(R.id.pb_down);
tv_pb = (TextView) findViewById(R.id.tv_pb);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TEXTVALUE:
System.out.println("-----------------------"
+ MainActivity.pb_count + "http://////"
+ MainActivity.size);
// 改變TEXTView
pb_num = (MainActivity.pb_count * 100) / MainActivity.size;
tv_pb.setText("當(dāng)前進(jìn)度是+" + pb_num + "%");
break;
default:
break;
}
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.down, menu);
return true;
}
//下載操作
public void downLoad(View v) {
// 改變變量值:
MainActivity.flag = true;
MainActivity.pb_count = 0;
path = et_url.getText().toString();
String threadNum_et = et_num.getText().toString();
if (TextUtils.isEmpty(path) || TextUtils.isEmpty(threadNum_et)) {
Toast.makeText(this, "不能為空", Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(this, "url:" + path + "--" + threadNum_et,
Toast.LENGTH_LONG).show();
// 轉(zhuǎn)換成數(shù)字
threadNum = Integer.valueOf(threadNum_et);
new Thread(new Runnable() {
@Override
public void run() {
try {
// 創(chuàng)建出URL對(duì)象
URL url = new URL(path);
// 創(chuàng)建出 HttpURLConnection對(duì)象
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 設(shè)置 發(fā)請(qǐng)求發(fā)送的方式
httpURLConnection.setRequestMethod("GET");
// 設(shè)置請(qǐng)求是否超時(shí)時(shí)間
httpURLConnection.setConnectTimeout(5000);
// 設(shè)置
httpURLConnection
.setRequestProperty("User-Agent",
" Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");
// 是否響應(yīng)成功
if (httpURLConnection.getResponseCode() == 200) {
// 獲取文件的大小
size = httpURLConnection.getContentLength();
System.out.println("文件的大小" + size);
// 設(shè)置進(jìn)度條的最大值
pb_thread.setMax(size);
// 創(chuàng)建文件 //保存到SD卡上
// 首先判斷是否擁有sdcard
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 獲取sdCard文件目錄對(duì)象
File sdFile = Environment
.getExternalStorageDirectory();
// 創(chuàng)建文件對(duì)象
File file = new File(sdFile, "youdao.exe");
RandomAccessFile accessFile = new RandomAccessFile(
file, "rwd");
// 設(shè)置文件的大小
accessFile.setLength(size);
// 每個(gè)線程下載的大小
blockSize = size / threadNum;
// 開三個(gè)線程 操作此文件
for (int i = 1; i <= threadNum; i++) {
// 1 2 3
// 計(jì)算出每個(gè)線程開始的位置
int startSize = (i - 1) * blockSize;
// 結(jié)束位置
int endSize = (i) * blockSize;
// 當(dāng)線程是最后一個(gè)線程的時(shí)候
if (i == threadNum) {
// 判斷文件的大小是否大于計(jì)算出來的結(jié)束位置
if (size > endSize) {
// 結(jié)束位置 等于 文件的大小
endSize = size;
}
}
// 為每個(gè)線程創(chuàng)建一個(gè)隨機(jī)的讀取
RandomAccessFile threadAccessFile = new RandomAccessFile(
file, "rwd");
new Thread(new DownLoadThread(i,
threadAccessFile, startSize, endSize,
path)).start();
}
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
//暫停操作
public void downPause(View v) {
Toast.makeText(this, "暫停", Toast.LENGTH_LONG).show();
this.flag = false;
}
}
復(fù)制代碼 代碼如下:
public class DownLoadThread implements Runnable {
// 下載文件的封裝
public RandomAccessFile accessFile;
// 線程下載文件的起始位置
public int startSize;
public int endSize;
// 文件下載的path路徑
public String path;
public int threadId; // 線程的標(biāo)識(shí)
public DownLoadThread(int threadId, RandomAccessFile accessFile,
int startSize, int endSize, String path) {
this.threadId = threadId;
this.accessFile = accessFile;
this.startSize = startSize;
this.endSize = endSize;
this.path = path;
}
@Override
public void run() {
// 執(zhí)行run方法
try {
// 創(chuàng)建文件到SD卡上去
// 首先判斷是否擁有sdcard
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 獲取sdCard文件目錄對(duì)象
File sdFile = Environment.getExternalStorageDirectory();
File threadFile = new File(sdFile, threadId + ".txt");
if (threadFile.exists()) {
// 讀取該文件的內(nèi)容
// 創(chuàng)建文件的輸入流對(duì)象
FileInputStream fis = new FileInputStream(threadFile);
// 采用工具類讀取
byte data[] = StreamTools.isToData(fis);
// 轉(zhuǎn)化成字符串
String threadLen = new String(data);
if ((threadLen != null) && (!"".equals(threadLen))) {
startSize = Integer.valueOf(threadLen);
// 解決 416bug的錯(cuò)誤
if (startSize > endSize) {
startSize = endSize - 1;
}
}
}
// 創(chuàng)建文件
// 創(chuàng)建URL對(duì)象
URL url = new URL(path);
// 創(chuàng)建HttpURLConnection對(duì)象
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 設(shè)置請(qǐng)求的頭
httpURLConnection.setRequestMethod("GET");
// 設(shè)置請(qǐng)求是否超時(shí)時(shí)間
httpURLConnection.setConnectTimeout(5000);
// 設(shè)置
httpURLConnection
.setRequestProperty("User-Agent",
" Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");
// 關(guān)鍵的設(shè)置
httpURLConnection.setRequestProperty("Range", "bytes="
+ startSize + "-" + endSize);
// 輸出當(dāng)前線程
System.out.println("當(dāng)前線程" + threadId + " 下載開始位置:" + startSize
+ " 下載結(jié)束位置:" + endSize);
// 響應(yīng)成功
// 設(shè)置隨機(jī)讀取文件的 開始位置
accessFile.seek(startSize);
// 獲取相應(yīng)流對(duì)象
InputStream is = httpURLConnection.getInputStream();
// 創(chuàng)建輸出流對(duì)象
byte buffer[] = new byte[1024];
int len = 0;
int threadTotal = 0;// 每個(gè)線程下載后保存記錄 /
while ((len = is.read(buffer)) != -1) {
accessFile.write(buffer, 0, len);
threadTotal += len;// 記錄你寫入的長度 //xml文件
//改變進(jìn)度條:
setProgressBar(len);
// 通過文件記錄文件下載的長度
FileOutputStream fos = new FileOutputStream(threadFile);
fos.write((threadTotal + "").getBytes());
fos.flush();
fos.close();
//發(fā)送handler消息
MainActivity.handler.sendEmptyMessage(MainActivity.TEXTVALUE);
if(!MainActivity.flag){
return;
}
}
accessFile.close();
is.close();
System.out.println(threadId + "線程執(zhí)行完畢");
// 線程操作
synchronized (MainActivity.class) {
MainActivity.threadCount++;
if (MainActivity.threadCount >= MainActivity.threadNum) {
for (int i = 1; i <= MainActivity.threadNum; i++) {
// 獲取sdCard上的文件
File deleteFile = new File(sdFile, i + ".txt");
if (deleteFile.exists()) {
// 文件刪除
deleteFile.delete();
}
}
}
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void setProgressBar(int len){
MainActivity.pb_count+=len;
MainActivity.pb_thread.setProgress(MainActivity.pb_count);
}
}
復(fù)制代碼 代碼如下:
public class StreamTools {
public static byte[] isToData(InputStream is) throws IOException{
// 字節(jié)輸出流
ByteArrayOutputStream bops = new ByteArrayOutputStream();
// 讀取數(shù)據(jù)的緩存區(qū)
byte buffer[] = new byte[1024];
// 讀取長度的記錄
int len = 0;
// 循環(huán)讀取
while ((len = is.read(buffer)) != -1) {
bops.write(buffer, 0, len);
}
// 把讀取的內(nèi)容轉(zhuǎn)換成byte數(shù)組
byte data[] = bops.toByteArray();
bops.flush();
bops.close();
is.close();
return data;
}
}
完整源碼
您可能感興趣的文章:
- android實(shí)現(xiàn)多線程下載文件(支持暫停、取消、斷點(diǎn)續(xù)傳)
- Android實(shí)現(xiàn)多線程下載文件的方法
- Android版多線程下載 仿下載助手(最新)
- Android編程開發(fā)實(shí)現(xiàn)帶進(jìn)度條和百分比的多線程下載
- Android FTP 多線程斷點(diǎn)續(xù)傳下載\上傳的實(shí)例
- Android多線程+單線程+斷點(diǎn)續(xù)傳+進(jìn)度條顯示下載功能
- Android多線程斷點(diǎn)續(xù)傳下載功能實(shí)現(xiàn)代碼
- Android實(shí)現(xiàn)多線程斷點(diǎn)下載的方法
- Android實(shí)現(xiàn)多線程下載圖片的方法
- Android線程池控制并發(fā)數(shù)多線程下載
相關(guān)文章
Android獲取LinearLayout的寬度和高度示例代碼
這篇文章主要介紹了android獲取LinearLayout的寬度和高度,如果想直接獲取在布局文件中定義的組件的寬度和高度,可以直接使用View.getLayoutParams().width和View.getLayoutParams().height,本文結(jié)合示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08
Android 防止多次重復(fù)點(diǎn)擊的三種方法的示例
本篇文章主要介紹了Android 防止多次重復(fù)點(diǎn)擊的三種方法的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03
Android開發(fā)之TabActivity用法實(shí)例詳解
這篇文章主要介紹了Android開發(fā)之TabActivity用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Android擴(kuò)展Activity實(shí)現(xiàn)標(biāo)簽頁效果的具體步驟與相關(guān)技巧,需要的朋友可以參考下2016-03-03
Android實(shí)現(xiàn)郵箱驗(yàn)證功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)郵箱驗(yàn)證功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
務(wù)必掌握的Android十六進(jìn)制狀態(tài)管理最佳實(shí)踐
這篇文章主要為大家介紹了務(wù)必掌握的Android十六進(jìn)制狀態(tài)管理最佳實(shí)踐,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Android中invalidate()和postInvalidate() 的區(qū)別及使用方法
Android中實(shí)現(xiàn)view的更新有兩組方法,一組是invalidate,另一組是postInvalidate,其中前者是在UI線程自身中使用,而后者在非UI線程中使用。本文給大家介紹Android中invalidate()和postInvalidate() 的區(qū)別及使用方法,感興趣的朋友一起學(xué)習(xí)吧2016-05-05
Android?Studio實(shí)現(xiàn)智能聊天
這篇文章主要為大家詳細(xì)介紹了Android?Studio實(shí)現(xiàn)智能聊天,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07

