Android編程開(kāi)發(fā)實(shí)現(xiàn)帶進(jìn)度條和百分比的多線程下載
本文實(shí)例講述了Android編程開(kāi)發(fā)實(shí)現(xiàn)帶進(jìn)度條和百分比的多線程下載。分享給大家供大家參考,具體如下:
繼上一篇《java多線程下載實(shí)例詳解》之后,可以將它移植到我們的安卓中來(lái),下面是具體實(shí)現(xiàn)源碼:
DownActivity.java:
package com.example.downloads;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.example.downloads.utils.DownLoadThread;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class DownActivity extends Activity {
// 聲明控件
// 路徑與線程數(shù)量
public EditText et_url, et_num;
// 進(jìn)度條
public static ProgressBar pb_thread;
// 顯示進(jìn)度的操作
public TextView tv_pb;
// 線程的數(shù)量
public static int threadNum = 3;
// 每個(gè)線程負(fù)責(zé)下載的大小
public int blockSize;
public static int threadCount;// 數(shù)量
// 訪問(wèn)的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_down);
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() {
@SuppressLint("HandlerLeak")
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case TEXTVALUE:
System.out.println("-------" + DownActivity.pb_count
+ "http://////" + DownActivity.size);
// 改變TEXTView
pb_num = (DownActivity.pb_count * 100) / DownActivity.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.main, menu);
return true;
}
public void downLoad(View v) {
DownActivity.flag = true;
DownActivity.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;
// 開(kāi)三個(gè)線程 操作此文件
for (int i = 1; i <= threadNum; i++) {
// 1 2 3
// 計(jì)算出每個(gè)線程開(kāi)始的位置
int startSize = (i - 1) * blockSize;
// 結(jié)束位置
int endSize = (i) * blockSize;
// 當(dāng)線程是最后一個(gè)線程的時(shí)候
if (i == threadNum) {
// 判斷文件的大小是否大于計(jì)算出來(lái)的結(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) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
/**
* 暫停操作
*
* @param v
*/
public void downPause(View v) {
Toast.makeText(this, "暫停", Toast.LENGTH_LONG).show();
this.flag = false;
}
}
DownLoadThread.java:
package com.example.downloads.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.example.downloads.DownActivity;
import android.os.Environment;
public class DownLoadThread implements Runnable {
public RandomAccessFile accessFile; // 每個(gè)線程 都擁有一個(gè)accessFile的文件對(duì)象 線程1 線程2 線程3
// 線程下載文件的起始位置
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 + " 下載開(kāi)始位置:" + startSize
+ " 下載結(jié)束位置:" + endSize);
// 響應(yīng)成功
// 設(shè)置隨機(jī)讀取文件的 開(kāi)始位置
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;// 記錄你寫(xiě)入的長(zhǎng)度 //xml文件
//改變進(jìn)度條:
setProgressBar(len);
// 通過(guò)文件記錄文件下載的長(zhǎng)度
FileOutputStream fos = new FileOutputStream(threadFile);
fos.write((threadTotal + "").getBytes());
fos.flush();
fos.close();
//發(fā)送handler消息
DownActivity.handler.sendEmptyMessage(DownActivity.TEXTVALUE);
if(!DownActivity.flag){
return;
}
}
accessFile.close();
is.close();
System.out.println(threadId + "線程執(zhí)行完畢");
// 線程操作
synchronized (DownActivity.class) {
DownActivity.threadCount++;
if (DownActivity.threadCount >= DownActivity.threadNum) {
for (int i = 1; i <= DownActivity.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){
DownActivity.pb_count+=len;
DownActivity.pb_thread.setProgress(DownActivity.pb_count);
}
}
StreamTools.java:
package com.example.downloads.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamTools {
public static byte[] isToData(InputStream is) throws IOException{
// 字節(jié)輸出流
ByteArrayOutputStream bops = new ByteArrayOutputStream();
// 讀取數(shù)據(jù)的緩存區(qū)
byte buffer[] = new byte[1024];
// 讀取長(zhǎng)度的記錄
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;
}
}
strings.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">downloads</string> <string name="action_settings">Settings</string> <string name="tv_down">文件下載的地址</string> <string name="tv_threadNum">線程數(shù)量</string> <string name="tv_num">0%</string> <string name="btn_text">下載</string> <string name="btn_pause">暫停</string> <string name="et_path">http://172.22.64.8:8080/doudou/youdao.exe</string> <string name="et_threadNum">3</string> </resources>
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".DownActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="@string/tv_down" />
<EditText
android:id="@+id/et_path"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:ems="10"
android:inputType="none"
android:text="@string/et_path" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/et_path"
android:text="@string/tv_threadNum" />
<EditText
android:id="@+id/et_threadNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_alignRight="@+id/et_path"
android:layout_below="@+id/textView2"
android:ems="10"
android:inputType="number"
android:text="@string/et_threadNum" />
<ProgressBar
android:id="@+id/pb_down"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/et_threadNum"
android:layout_alignRight="@+id/et_threadNum"
android:layout_below="@+id/et_threadNum"
android:layout_marginTop="14dp" />
<TextView
android:id="@+id/tv_pb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/pb_down"
android:layout_marginTop="24dp"
android:text="@string/tv_num" />
<Button
android:id="@+id/btn_down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/pb_down"
android:layout_below="@+id/tv_pb"
android:layout_marginTop="32dp"
android:onClick="downLoad"
android:text="@string/btn_text" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btn_down"
android:layout_below="@+id/btn_down"
android:layout_marginTop="16dp"
android:onClick="downPause"
android:text="@string/btn_pause" />
</RelativeLayout>
效果如下:

最后要注意的是別忘了在項(xiàng)目清單文件中加入權(quán)限:
<!-- SDCard權(quán)限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 訪問(wèn)網(wǎng)絡(luò)的權(quán)限 --> <uses-permission android:name="android.permission.INTERNET" />
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- android中多線程下載實(shí)例
- android實(shí)現(xiàn)多線程下載文件(支持暫停、取消、斷點(diǎn)續(xù)傳)
- Android實(shí)現(xiàn)多線程下載文件的方法
- Android版多線程下載 仿下載助手(最新)
- 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)文章
自定義TextView跑馬燈效果可控制啟動(dòng)/停止/速度/焦點(diǎn)
Android自帶的跑馬燈效果不太好控制,不能控制速度,不能即時(shí)停止和啟動(dòng),而且還受焦點(diǎn)的影響不已,由于項(xiàng)目需求需所以自己寫(xiě)了一個(gè)自定義的TextView,感興趣的朋友可以了解下2013-01-01
Android XRecyclerView實(shí)現(xiàn)多條目加載
這篇文章主要為大家詳細(xì)介紹了Android XRecyclerView實(shí)現(xiàn)多條目加載效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
ListView上滑和下滑,顯示和隱藏Toolbar的實(shí)現(xiàn)方法
下面小編就為大家分享一篇ListView上滑和下滑,顯示和隱藏Toolbar的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Android函數(shù)抽取殼的實(shí)現(xiàn)代碼
很早之前就想寫(xiě)這類的殼,最近終于把它做出來(lái)了,取名為dpt,下面把代碼分享出來(lái),對(duì)Android函數(shù)抽取殼的實(shí)現(xiàn)代碼感興趣的朋友一起看看吧2022-01-01
Android編程之線性布局LinearLayout實(shí)例簡(jiǎn)析
這篇文章主要介紹了Android編程之線性布局LinearLayout用法,結(jié)合實(shí)例形式簡(jiǎn)單分析了Android線性布局的使用技巧,需要的朋友可以參考下2016-01-01
Android 浮動(dòng)編輯框的具體實(shí)現(xiàn)代碼
本篇文章主要介紹了Android 浮動(dòng)編輯框的具體實(shí)現(xiàn)代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10
Android自定義控件實(shí)現(xiàn)底部菜單(下)
這篇文章主要為大家詳細(xì)介紹了Android自定義控件實(shí)現(xiàn)底部菜單的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
利用Kotlin的協(xié)程實(shí)現(xiàn)簡(jiǎn)單的異步加載詳解
這篇文章主要給大家介紹了關(guān)于利用Kotlin的協(xié)程實(shí)現(xiàn)簡(jiǎn)單的異步加載的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03
Android 抽屜效果的導(dǎo)航菜單實(shí)現(xiàn)代碼實(shí)例
本篇文章主要介紹了Android 抽屜效果的導(dǎo)航菜單實(shí)現(xiàn)代碼實(shí)例,這種側(cè)滑的抽屜效果的菜單很好,有興趣的可以了解一下。2016-12-12

