實現多線程下載的大概思路:(假設文件大小是6M,共有三條線程同時執行)
●首先要根據訪問的URL路徑去調用openConnection方法,得到HttpUrlConnection對象,HttpUrlConnection對象調用它的方法得到下載文件的長度,然後設置本地文件的長度。
點擊(此處)摺疊或打開
-
int length = HttpURLConnection.getContentLength();
- RandomAccessFile file = new RandomAccessFile("calendar_setup.exe","rw");
- file.setLength(length);
RandomAccessFile同時將FileInputStream和FileOutputStream整合到一起,而且支持將從文件任意字節處都或寫數據;File類只是將文件作爲整體來處理文件,不能讀寫文件
●根據文件長度和線程數計算每條線程下載的數據長度和下載位置,如文件長度爲6M,線程數爲3,那麼每條線程下載數據的長度爲2M,
問題:在下載時如何指定這些線程開始下載的位置?→HTTP協議
●使用HTTP的Range頭字段指定每條線程從文件的什麼位置開始下載,如指定從文件的2M位置開始下載:
點擊(此處)摺疊或打開
- HttpURLConnection.setRequestProperty("Range","bytes=2097152-");
●保存文件,使用RandomAccessFile類指定每條線程從本地的什麼位置開始寫入數據
點擊(此處)摺疊或打開
-
RandomAccessFile file = new RandomAccessFile("calendar_setup.exe","rw");
- file.seek(2097152);
小案例:
●編寫佈局文件,主要有一個進度條,一個Button,一個EditText
點擊(此處)摺疊或打開
-
<?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"
-
>
-
<TextView
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
-
android:text="下載"
-
/>
-
<EditText
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
-
android:hint="請輸入下載路徑"
-
android:text="http://file1.updrv.com/soft/rili/calendar_setup.exe"
-
android:id = "@+id/et_path"/>
-
<ProgressBar
-
android:id="@+id/bar"
-
style="?android:attr/progressBarStyleHorizontal"
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"/>
-
<TextView
-
android:id="@+id/tv_process"
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"/>
-
<Button
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
-
android:text="開始下載"
-
android:id="@+id/bt"/>
- </LinearLayout>
●編寫activity文件,
點擊(此處)摺疊或打開
- public class DownLoadActivity extends Activity implements OnClickListener {
-
//定義相關控件
-
ProgressBar bar;
-
Button bt;
-
TextView tv ;
-
EditText et_text;
-
boolean flag = true;
-
boolean stopflag = false;
-
Handler handler = new Handler(){
-
-
@Override
-
public void handleMessage(Message msg) {
-
bar.setProgress(total);
-
int max = bar.getMax();
-
if (total>=(max-1)) {
-
total = max;
-
flag = false;
-
}
-
int result = total*100/max;
-
tv.setText("當前進度:"+result+"%");
-
super.handleMessage(msg);
-
}
-
-
};
-
int total = 0;
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
//初始化相關控件
-
bar = (ProgressBar) this.findViewById(R.id.bar);
-
bt = (Button)this.findViewById(R.id.bt);
-
tv = (TextView)this.findViewById(R.id.tv_process);
-
et_text=(EditText)this.findViewById(R.id.et_path);
-
bt.setOnClickListener(this);
-
}
-
@Override
-
public void onClick(View v) {
-
switch (v.getId()) {
-
case R.id.bt:
-
if ("開始下載".equals(bt.getText().toString().trim())) {
-
bt.setText("暫停");
-
stopflag = false;
-
}else {
-
bt.setText("開始下載");
-
stopflag=true;
-
}
-
new Thread(){
-
-
@Override
-
public void run() {
-
while (flag) {
-
try {
-
sleep(1000);
-
Message message = new Message();
-
//通知更新UI
-
handler.sendMessage(message);
-
} catch (Exception e) {
-
// TODO: handle exception
-
}
-
}
-
super.run();
-
}
-
-
}.start();
-
//得到下載路徑
-
String path = et_text.getText().toString().trim();
-
if ("".equals(path)) {
-
Toast.makeText(this, "路徑不能爲空", 0).show();
-
return;
-
}
-
try {
-
URL url = new URL(path);
-
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
//設置請求的相關參數
-
conn.setRequestMethod("GET");
-
conn.setConnectTimeout(5000);
-
conn.setRequestProperty("User-Agent",
-
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
-
int code = conn.getResponseCode();
-
if (code ==200) {
-
int length = conn.getContentLength();
-
RandomAccessFile file = new RandomAccessFile("/mnt/sdcard/" + getFileName(path), "rwd");
-
//設置文件長度
-
file.setLength(length);
-
//設置進度條最大值
-
bar.setMax(length);
-
//建立3條線程下載數據
-
int threadNO = 3;
-
//每條線程下載數據的大小
-
int blocksize = length/threadNO;
-
-
for (int i = 0; i <threadNO; i++) {
-
int startposition = i*blocksize;//每條線程下載的開始位置
-
int endposition = (i+1)*blocksize;//每條線程下載的結束位置
-
if (i==(threadNO-1)) {
-
endposition = length;//如果整個文件的大小不爲線程個數的整數倍,則最後一個線程的結束位置即爲文件的總長度
-
}
-
DownLoadTask task = new DownLoadTask(i,path,startposition,endposition);
-
task.start();
-
}
-
}
-
} catch (Exception e) {
-
// TODO: handle exception
-
Toast.makeText(this,"下載出現異常",0).show();
-
}
-
-
break;
-
}
-
}
-
class DownLoadTask extends Thread{
-
int threadid;
-
String path;
-
int startposition;
-
int endposition;
-
public DownLoadTask(int threadid, String path, int startposition,
-
int endposition) {
-
this.threadid = threadid;
-
this.path = path;
-
this.startposition = startposition;
-
this.endposition = endposition;
-
}
-
@Override
-
public void run() {
-
// TODO Auto-generated method stub
-
try {
-
//爲每個線程創建一個文件用於記錄暫停下載時當時已下載的數據大小
-
File postionfile = new File("/mnt/sdcard/" + threadid + ".txt");
-
URL url = new URL(path);
-
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
System.out.println("線程" + threadid + "正在下載
" + "開始位置 : "
-
+ startposition + "結束位置 " + endposition);
-
if (postionfile.exists()) {
-
FileInputStream is = new FileInputStream(postionfile);
-
//處理流信息得到以下載的字節數大小
-
byte[] result = StreamTool.getByte(is);
-
String str = new String(result);
-
if (!"".equals(str)) {
-
//如果postionfile中有記錄,則改變開始下載的位置
-
int newstartposition = Integer.parseInt(str);
-
if (newstartposition>startposition) {
-
startposition = newstartposition;
-
}
-
}
-
}
-
-
conn.setRequestProperty("Range", "bytes=" + startposition + "-"
-
+ endposition);
-
conn.setRequestMethod("GET");
-
conn.setConnectTimeout(5000);
-
conn.setRequestProperty("User-Agent",
-
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
-
InputStream is = conn.getInputStream();
-
RandomAccessFile file = new RandomAccessFile("/mnt/sdcard/"
-
+ getFileName(path), "rwd");
-
file.seek(startposition);
-
byte[] buffer = new byte[1024];
-
int len = 0;
-
int currentPosition = startposition;
-
while ((len = is.read(buffer))!=-1) {
-
if (stopflag) {
-
return;
-
}
-
file.write(buffer, 0, len);
-
synchronized (DownLoadActivity.this) {
-
total+=len;
-
}
-
//記錄當前線程以下載的數據
-
currentPosition+=len;
-
String position = currentPosition+"";
-
FileOutputStream out = new FileOutputStream(postionfile);
- //把記錄寫入文件
-
out.write(position.getBytes());
-
out.flush();
-
out.close();
-
-
}
-
file.close();
-
System.out.println("線程"+threadid+"下載完畢");
-
if (postionfile.exists()) {
-
postionfile.delete();
-
}
-
} catch (Exception e) {
-
}
-
super.run();
-
}
-
}
-
public String getFileName(String path){
-
int start = path.lastIndexOf("/")+1;
-
return path.substring(start, path.length());
-
}
- }
●最後一個就是一個處理輸入流的工具類,返回字節數:
點擊(此處)摺疊或打開
-
public class StreamTool {
-
public static byte[] getByte(InputStream is) throws Exception{
-
ByteArrayOutputStream out = new ByteArrayOutputStream();
-
int len = 0;
-
byte[] b = new byte[1024];
-
while ((len = is.read(b))!=-1) {
-
out.write(b, 0, len);
-
}
-
is.close();
-
out.flush();
-
return out.toByteArray();
-
}
- }