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

Android 實現多執行緒斷點續傳下載

編輯:關於 Android 程式設計

大型檔案下載若每次都從頭開始,既耗時又浪費流量。本文實作一個多執行緒的斷點續傳下載器:檔案下載中途中斷後,能從既有進度繼續,並以進度條即時顯示。核心概念是為每個執行緒維護一個記錄檔,保存下載位置,重新進入時讀取記錄續傳,全部完成後自動清理暫存檔。

步驟一:定義版面所需的字串資源

先規劃版面要用到的屬性名稱與內容。

步驟二:宣告權限

需要網路與 SD 卡寫入權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.INTERNET"/>

步驟三:規劃開始畫面

畫面使用兩個 TextView、一個 EditText、一個 Button 與一個 ProgressBar 構成,效果如下:

步驟四:撰寫 MainActivity 主要邏輯

程式會先取得伺服器檔案大小,將其均分給三個執行緒,各自負責一段範圍,並以 RandomAccessFile 隨機寫入對應位置。

package www.csdn.net.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import www.csdn.net.utils.StreamTools;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DownloadActivity extends Activity {
    private int threadNum = 3;
    private int threadRunning = 3;
    private EditText et_url;
    private ProgressBar progressBar;
    private TextView tv_pb;
    private int currentProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        et_url = (EditText) findViewById(R.id.et_url);
        progressBar = (ProgressBar) findViewById(R.id.pb_down);
        tv_pb = (TextView) findViewById(R.id.tv_pb);

        File sdDir = Environment.getExternalStorageDirectory();
        File pbFile = new File(sdDir, "pb.txt");
        InputStream is = null;
        try {
            if (pbFile.exists()) {
                is = new FileInputStream(pbFile);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (is != null) {
            String value = StreamTools.streamToStr(is);
            String[] arr = value.split(";");
            progressBar.setMax(Integer.valueOf(arr[0]));
            currentProgress = Integer.valueOf(arr[1]);
            progressBar.setProgress(currentProgress);
            tv_pb.setText("目前的進度是:" + arr[2]);
        }
    }

    public void downLoadFile(View v) {
        final String spec = et_url.getText().toString();
        if (TextUtils.isEmpty(spec)) {
            Toast.makeText(this, "下載位址不能為空", Toast.LENGTH_LONG).show();
        } else {
            new Thread() {
                public void run() {
                    try {
                        URL url = new URL(spec);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setReadTimeout(5000);
                        conn.setConnectTimeout(5000);
                        if (conn.getResponseCode() == 200) {
                            int fileLength = conn.getContentLength();
                            progressBar.setMax(fileLength);
                            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                File sdFile = Environment.getExternalStorageDirectory();
                                String fileName = spec.substring(spec.lastIndexOf("/") + 1);
                                File file = new File(sdFile, fileName);
                                RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
                                accessFile.setLength(fileLength);
                                accessFile.close();
                                int threadSize = fileLength / threadNum;
                                for (int threadId = 1; threadId <= threadNum; threadId++) {
                                    int startIndex = (threadId - 1) * threadSize;
                                    int endIndex = threadId * threadSize - 1;
                                    if (threadId == threadNum) {
                                        endIndex = fileLength - 1;
                                    }
                                    new DownLoadThread(threadId, startIndex, endIndex, spec).start();
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }
}

每個下載執行緒會先檢查自己的記錄檔,若有既存進度則從該處續傳,並透過 Range 標頭向伺服器請求指定範圍的位元組。

class DownLoadThread extends Thread {
    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() {
        try {
            File sdFile = Environment.getExternalStorageDirectory();
            File recordFile = new File(sdFile, threadId + ".txt");
            if (recordFile.exists()) {
                InputStream is = new FileInputStream(recordFile);
                String value = StreamTools.streamToStr(is);
                startIndex = Integer.parseInt(value);
            }
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
            if (conn.getResponseCode() == 206) {
                InputStream is = conn.getInputStream();
                String fileName = path.substring(path.lastIndexOf("/") + 1);
                File file = new File(sdFile, fileName);
                RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                raf.seek(startIndex);
                int len = 0;
                byte b[] = new byte[1024 * 1024];
                int total = 0;
                while ((len = is.read(b)) != -1) {
                    RandomAccessFile threadFile = new RandomAccessFile(new File(sdFile, threadId + ".txt"), "rwd");
                    threadFile.writeBytes((startIndex + total) + "");
                    threadFile.close();
                    raf.write(b, 0, len);
                    total += len;
                    synchronized (DownloadActivity.this) {
                        currentProgress += len;
                        progressBar.setProgress(currentProgress);
                        final String percent = currentProgress * 100l / progressBar.getMax() + "%";
                        DownloadActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                tv_pb.setText("目前的進度是:" + percent);
                            }
                        });
                    }
                }
                raf.close();
                is.close();
                deleteRecordFiles();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

另外可封裝一個 StreamTools 工具類,將輸入流轉為字串,方便讀取記錄檔內容:

package www.csdn.net.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamTools {
    public static String streamToStr(InputStream is) {
        String value = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte b[] = new byte[1024];
            while ((len = is.read(b)) != -1) {
                baos.write(b, 0, len);
            }
            baos.close();
            is.close();
            value = new String(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }
}

步驟五:執行結果

程式運行後可看到多執行緒協同下載,SD 卡中會產生暫存的記錄檔,下載完成後會自動刪除:

常見 Bug 排查

若程式無法正常下載,可優先檢查:是否遺漏網路權限、伺服器是否啟動、下載路徑是否正確、控制項是否正確取得等。

另外,若進度條顯示為負數,通常是因為百分比計算時數值溢出了 int 範圍。解法是在計算時將 100 加上 l 轉為 long 型別,例如:String percent = currentProgress * 100l / progressBar.getMax() + "%"。

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