Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 多線程斷點下載的實作原理與技巧

編輯:關於 Android 程式設計

多線程下載是提升下載速度的常見手段——透過開啟多個線程共同處理同一個任務,讓整體執行效率顯著提升。我們手機裡的應用商店下載器,背後多半就是這樣的機制,而且還支援斷點續傳:任務被強制中斷後,下次仍能從中斷處接續下載。那麼,斷點下載究竟該如何實作呢?

首先要釐清一個觀念:多線程下載並不是線程越多越快。當線程數量增加到一定程度後,單一線程的執行效率反而會下降,因此線程數需要有所節制。根據實測,下載同一任務時 5 到 8 個線程算是比較高效的配置;一旦超過 10 個,效率往往不升反降(前提是網速大致相同的情況下)。

那麼,多線程下載同一任務背後的原理是什麼?先看下面這張示意圖:

圖中很直白地說明了原理:把一個任務切成多個區塊,再開啟多個線程分別下載對應的部分即可。首先要解決的問題是,如何讓每個線程各下載各的區塊而不越界。我們先用純 Java 實作,最後再移植到 Android 上。

 public class Download { public static int threadCount = 5; //線程開啟的數量.. public static void main(String[] args) { // TODO Auto-generated method stub String path = "https://192.168.199.172:8080/jdk.exe"; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int status = conn.getResponseCode(); if(status == 200){ int length = conn.getContentLength(); System.out.println(length); int blocksize = length/threadCount; //將文件長度進行平分.. for(int threadID=1; threadID<=threadCount;threadID++){ int startIndex = (threadID-1)*blocksize; //開始位置的求法.. int endIndex = threadID*blocksize -1; //結束位置的求法.. /** * 如果一個文件的長度無法整除線程數.. * 那麼最後一個線程下載的結束位置需要設置文件末尾.. * */ if(threadID == threadCount){ endIndex = length; } System.out.println("線程下載位置:"+startIndex+"---"+endIndex); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

這一步只是先連上伺服器取得檔案長度,並計算出每個線程各自的起點與終點。有了這些位置資訊,接下來就要真正開啟線程去下載了,因此我們需要自行定義下載的過程。

先理清思路:既然是斷點下載,那麼一旦發生中斷,下次就必須從原本斷掉的位置續傳,已經下載過的區段則不必重來。為此我們得記錄每一次的下載進度;而當檔案下載完成後,這些記錄檔就該清除。掌握這兩點,程式就好寫了。

 //下載線程的定義.. public static class DownLoadThread implements Runnable{ private int threadID; private int startIndex; private int endIndex; private String path; public DownLoadThread(int threadID,int startIndex,int endIndex,String path){ this.threadID = threadID; this.startIndex = startIndex; this.endIndex = endIndex; this.path = path; } @Override public void run() { // TODO Auto-generated method stub try { //判斷上一次是否下載完畢..如果沒有下載完畢需要繼續進行下載..這個文件記錄了上一次的下載位置.. File tempfile =new File(threadID+".txt"); if(tempfile.exists() && tempfile.length()>0){ FileInputStream fis = new FileInputStream(tempfile); byte buffer[] = new byte[1024]; int leng = fis.read(buffer); int downlength = Integer.parseInt(new String(buffer,0,leng));//從上次下載後的位置開始下載..重新擬定開始下載的位置.. startIndex = downlength; fis.close(); } URL url = new URL(path); HttpURLConnection conn =(HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex); int status = conn.getResponseCode(); //206也表示服務器響應成功.. if(status == 206){ //獲取服務器返回的I/O流..然後將數據寫入文件當中.. InputStream in = conn.getInputStream(); //文件寫入開始..用來保存當前需要下載的文件.. RandomAccessFile raf = new RandomAccessFile("jdk.exe", "rwd"); raf.seek(startIndex); int len = 0; byte buf[] =new byte[1024]; //記錄已經下載的長度.. int total = 0; while((len = in.read(buf))!=-1){ //用於記錄當前下載的信息.. RandomAccessFile file =new RandomAccessFile(threadID+".txt", "rwd"); total += len; file.write((total+startIndex+"").getBytes()); file.close(); //將數據寫入文件當中.. raf.write(buf, 0, len); } in.close(); raf.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //如果所有的線程全部下載完畢後..也就是任務完成..清除掉所有原來的記錄文件.. runningThread -- ; if(runningThread==0){ for(int i=1;i<threadCount;i++){ File file = new File(i+".txt"); file.delete(); } } } } } 

如此一來,檔案數據的下載流程就完成了。實測之下,一個 13M 的檔案在 5 個線程合力下約 12 秒完成(網速穩定在 300k 時),單線程則約需 15 秒,看似只差兩秒;但別忘了檔案一大,差距就明顯了。實測一個 90M 的檔案,5 線程約 1 分 20 秒,單線程則要 2 分鐘左右,差距可觀。

對照之下,多線程下載確實更具優勢。雖然一般 App 很少超過 50M,但遊戲動輒 100 至 200M,多線程能明顯提升下載的效率。此外,也可以改用線程池來管理這些線程,讓資源的調度更省心。

在純 Java 專案中寫好下載程式後,就能移植到 Android 應用中,不過有幾個細節值得留意,這裡特別強調一下:

 package com.example.mutithread; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import android.os.Bundle; import android.os.Handler; import android.os.Message; 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 MainActivity extends Activity { private EditText et; private ProgressBar pb; public static int threadCount = 5; public static int runningThread=5; public int currentProgress=0; //當前進度值.. private TextView tv; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg){ switch (msg.what) { case 1: Toast.makeText(getApplicationContext(), msg.obj.toString(), 0).show(); break; case 2: break; case 3: tv.setText("當前進度:"+(pb.getProgress()*100)/pb.getMax()); default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et = (EditText) findViewById(R.id.et); pb =(ProgressBar) findViewById(R.id.pg); tv= (TextView) findViewById(R.id.tv); } public void downLoad(View v){ final String path = et.getText().toString().trim(); if(TextUtils.isEmpty(path)){ Toast.makeText(this, "下載路徑錯誤", Toast.LENGTH_LONG).show(); return ; } new Thread(){ // String path = "https://192.168.199.172:8080/jdk.exe"; public void run(){ try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int status = conn.getResponseCode(); if(status == 200){ int length = conn.getContentLength(); System.out.println("文件總長度"+length); pb.setMax(length); RandomAccessFile raf = new RandomAccessFile("/sdcard/setup.exe","rwd"); raf.setLength(length); raf.close(); //開啟5個線程來下載當前資源.. int blockSize = length/threadCount ; for(int threadID=1;threadID<=threadCount;threadID++){ int startIndex = (threadID-1)*blockSize; int endIndex = threadID*blockSize -1; if(threadID == threadCount){ endIndex = length; } System.out.println("線程"+threadID+"下載:---"+startIndex+"--->"+endIndex); new Thread(new DownLoadThread(threadID, startIndex, endIndex, path)).start() ; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }.start(); } /** * 下載線程.. * */ public class DownLoadThread implements Runnable{ private int ThreadID; private int startIndex; private int endIndex; private String path; public DownLoadThread(int ThreadID,int startIndex,int endIndex,String path){ this.ThreadID = ThreadID; this.startIndex = startIndex; this.endIndex = endIndex; this.path = path; } @Override public void run() { // TODO Auto-generated method stub URL url; try { //檢查是否存在還未下載完成的文件... File tempfile = new File("/sdcard/"+ThreadID+".txt"); if(tempfile.exists() && tempfile.length()>0){ FileInputStream fis = new FileInputStream(tempfile); byte temp[] =new byte[1024]; int leng = fis.read(temp); int downlength = Integer.parseInt(new String(temp,0,leng)); int alreadydown = downlength -startIndex; currentProgress += alreadydown;//發生斷點之後記錄下載的文件長度.. startIndex = downlength; fis.close(); } url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex); conn.setConnectTimeout(5000); //獲取響應碼.. int status =conn.getResponseCode(); if(status == 206){ InputStream in = conn.getInputStream(); RandomAccessFile raf =new RandomAccessFile("/sdcard/jdk.exe", "rwd"); //文件開始寫入.. raf.seek(startIndex); int len =0; byte[] buffer =new byte[1024]; //已經下載的數據長度.. int total = 0; while((len = in.read(buffer))!=-1){ //記錄當前數據下載的長度... RandomAccessFile file = new RandomAccessFile("/sdcard/"+ThreadID+".txt", "rwd"); raf.write(buffer, 0, len); total += len; System.out.println("線程"+ThreadID+"total:"+total); file.write((total+startIndex+"").getBytes()); file.close(); synchronized (MainActivity.this) { currentProgress += len; //獲取當前總進度... //progressBar progressDialog可以直接在子線程內部更新UI..由於源碼內部進行了特殊的處理.. pb.setProgress(currentProgress); //更改界面上的進度條進度.. Message msg =Message.obtain(); //復用以前的消息..避免多次new... msg.what = 3; handler.sendMessage(msg); } } raf.close(); in.close(); System.out.println("線程:"+ThreadID+"下載完畢"); }else{ System.out.println("線程:"+ThreadID+"下載失敗"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Message msg = new Message(); msg.what = 1; msg.obj = e; handler.sendMessage(msg); }finally{ synchronized (MainActivity.this) { runningThread--; if(runningThread == 0){ for(int i=1;i<=threadCount;i++){ File file = new File("/sdcard/"+i+".txt"); file.delete(); } Message msg =new Message(); msg.what = 2; msg.obj ="下載完畢"; handler.sendMessage(msg); } } } } } @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; } } 

以上即為移植後的完整程式碼。這裡定義了一個 ProgressBar 進度條與一個 TextView 來同步顯示下載進度。在 Android 中,耗時操作不能放在主線程執行,因此必須另開子線程;但子線程又不能直接更新 UI,於是就需要透過 Handler 與 Message 機制來完成介面更新。

不過你會發現,上面的程式碼竟在子線程裡直接更新了 ProgressBar。這是因為 ProgressBar 與 ProgressDialog 是兩個特例,它們允許在子線程中更新屬性。我們來看看源碼的實作:

 private synchronized void refreshProgress(int id, int progress, boolean fromUser) { if (mUiThreadId == Thread.currentThread().getId()) { //如果當前運行的線程和主線程相同..那麼更新進度條.. doRefreshProgress(id, progress, fromUser, true); } else { //如果不滿足上面說的情況.. if (mRefreshProgressRunnable == null) { mRefreshProgressRunnable = new RefreshProgressRunnable();//那麼新建立一個線程..然後執行下面的過程.. } final RefreshData rd = RefreshData.obtain(id, progress, fromUser); //獲取消息隊列中的消息.. mRefreshData.add(rd); if (mAttached && !mRefreshIsPosted) { post(mRefreshProgressRunnable); //主要是這個地方..調用了post方法..將當前運行的線程發送到消息隊列當中..那麼這個線程就可以在UI中運行了..因此這一步是決定因素.. mRefreshIsPosted = true; } } } 

正是因為源碼內部呼叫了 post 方法,把當前線程放進消息佇列,UI 中的 Looper 線程便會接手處理,於是這個線程就能在 UI 中執行——這也正是我們得以在子線程內更新 ProgressBar 的原因。但也正因如此,若想更新 TextView 這類一般控件,仍然得透過 Handler 與 Message 機制來完成,這一點要特別留意。
移植後的程式碼其實變動不大,如此一來,一個能在 Android 上運行的多線程斷點下載器就完成了。

以上就是本文的全部內容,希望對大家學習 Android 軟體編程有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved