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

Android 開發步步為營之 108:單線程下載斷點續傳實戰

編輯:關於 Android 程式設計

在 Android 開發中,下載幾乎是必備能力——無論是下載安裝包還是圖片。设想一下:用戶正用 4G 下載一個一百多兆的遊戲包,好不容易下到 90M,手機卻突然沒電了。等充好電重新打開,如果又從頭開始下載,白白浪費的流量足以讓人崩潰。這正是斷點續傳存在的意義:中斷後能從上次的位置接著下,而不是推倒重來。

斷點續傳其實也可以借助多線程來實現,但本篇先不把事情搞複雜,只用單線程完成一個下載任務:萬一被中斷,下次再點擊下載時,就從斷點繼續。下面就以「下載 360 手機衛士安裝包」為例,動手做個實驗,並附上完整的 Demo 代碼。

1、activity_resume_download.xml 下載頁面

<linearlayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android">
    <textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="斷點續傳測試">
        <button android:id="@+id/btn_download" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="開始下載"></button>
        <button android:id="@+id/btn_cancel" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="取消下載">
            <progressbar android:id="@+id/progressBar" android:layout_gravity="center_horizontal" android:layout_height="20dp" android:layout_width="match_parent" >
            </progressbar>
        </button>
    </textview>
</linearlayout>

2、ResumeDownloadActivity.java

package com.figo.study.activity;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.figo.study.R;
import com.figo.study.mgr.DownloadMgr;
import com.figo.study.utils.FileUtils;
import java.io.File;
public class ResumeDownloadActivity extends Activity implements View.OnClickListener {
    String tag = "ResumeDownloadActivity";
    ProgressBar mProgressBar;
    String downloadUrl = "https://msoftdl.360.cn/mobilesafe/shouji360/360safe/500192/360MobileSafe.apk";
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resume_download);
        findViewById(R.id.btn_download).setOnClickListener(this);
        findViewById(R.id.btn_cancel).setOnClickListener(this);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    }
    private final Handler msgHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(getApplicationContext(), msg.getData().get("msg").toString(), Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
    @Override public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_download:
                String directory = FileUtils.getStorageDirectory();
                String fileName = directory + File.separator + getFileName(downloadUrl);
                DownloadMgr.getInstance().addTask(downloadUrl, fileName, new DownloadMgr.Callback() {
                    @Override public void onProgress(long progress, long total) {
                        super.onProgress(progress, total);
                        mProgressBar.setProgress((int) (100 * progress / total));
                    }
                    @Override public void onStart() {
                        super.onStart();
                        sendMsg("start");
                    }
                    @Override public void onSuccess() {
                        super.onSuccess();
                        Log.i(tag, "success");
                        sendMsg("success");
                    }
                    @Override public void onFailed(boolean cancelled, String msg) {
                        super.onFailed(cancelled, msg);
                        Log.e(tag, msg);
                        //進程間通信還是用Handler比較靠譜
                        sendMsg(msg);
                    }
                });
                break;
            case R.id.btn_cancel:
                DownloadMgr.getInstance().cancelTask(downloadUrl);
                break;
        }
    }
    private String getFileName(String downloadUrl) {
        return downloadUrl.substring(downloadUrl.lastIndexOf("/"));
    }
    private void sendMsg(String msg) {
        Message msgNew = new Message();
        msgNew.what = 0;
        Bundle bundle = new Bundle();
        bundle.putString("msg", msg);
        msgNew.setData(bundle);
        msgHandler.sendMessage(msgNew);
    }
}

3、下載工具類 DownloadMgr.java

package com.figo.study.mgr;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.figo.study.activity.MyApplication;
import com.figo.study.utils.CommonUtil;
import com.figo.study.utils.IOUtil;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class DownloadMgr {
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    Executor mExecutor = Executors.newFixedThreadPool(MAXIMUM_POOL_SIZE);
    static DownloadMgr mDownloadMgr;
    static Object obj = new Object();
    HashMap<String, DownloadTask> mTasks = new HashMap<String, DownloadTask>();
    public static void init() { getInstance(); }
    public static DownloadMgr getInstance() {
        synchronized (obj) {
            if (mDownloadMgr == null) {
                mDownloadMgr = new DownloadMgr();
            }
        }
        return mDownloadMgr;
    }
    public void addTask(String downloadUrl, String filePath, Callback callback) {
        if (!mTasks.containsKey(downloadUrl)) {
            mTasks.put(downloadUrl, new DownloadTask(downloadUrl, filePath, callback));
        }
        mTasks.get(downloadUrl).startDownload();
    }
    public void removeTask(String downloadUrl, String filePath, Callback callback) {
        if (mTasks.containsKey(downloadUrl)) {
            mTasks.get(downloadUrl).cancel();
        }
        mTasks.remove(downloadUrl);
    }
    public class DownloadTask implements Runnable {
        private String downloadUrl;
        private String filePath;
        Callback callback;
        public DownloadTask(String downloadUrl, String filePath, Callback callback) {
            this.downloadUrl = downloadUrl;
            this.filePath = filePath;
            this.callback = callback;
        }
        public void startDownload() { mExecutor.execute(this); }
        @Override public void run() { runResumable(downloadUrl, filePath, callback); }
        synchronized boolean cancel() {
            if (thread == null) return false;
            thread.interrupt();
            return true;
        }
    }
    Thread thread;
    public void runResumable(String downloadUrl, String filePath, Callback callback) {
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        thread = Thread.currentThread();
        final Context ctx = MyApplication.getInstance();
        String msg = "";
        boolean interrupted = false;
        HttpURLConnection conn = null;
        long resumePosition = 0;
        final File file = new File(filePath);
        try {
            final File parent = file.getParentFile();
            if (!parent.exists()) { parent.mkdirs(); }
            if (!file.exists()) { file.createNewFile(); }
            callback.onStart();
            //非wifi環境不下載
            if (!isWifiActive(ctx)) {
                msg = "請在wifi環境下下載";
                callback.onFailed(true, msg);
                return;
            }
            //斷點續傳的關鍵:取已下載文件的長度作為起始位置
            resumePosition = file.exists() ? file.length() : 0;
            conn = (HttpURLConnection) new URL(downloadUrl).openConnection();
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Java/Android");
            conn.setRequestProperty("Connection", "close");
            conn.setRequestProperty("Http-version", "HTTP/1.1");
            conn.setRequestProperty("Cache-Control", "no-transform");
            if (resumePosition > 0) {
                //斷點續傳的關鍵設置Range
                conn.setRequestProperty("Range", "bytes=" + resumePosition + "-");
            }
            conn.connect();
            final int responseCode = conn.getResponseCode();
            if (responseCode == 416) {
                msg = "已經下載!";
                callback.onFailed(true, msg);
                return;
            }
            if (responseCode != 200 && responseCode != 206) {
                msg = "網絡繁忙,請稍後再試!";
                callback.onFailed(true, msg);
                return;
            }
            long fileLength = conn.getContentLength();
            InputStream is = new BufferedInputStream(conn.getInputStream());
            FileOutputStream fos = new FileOutputStream(file, resumePosition > 0);
            try {
                int read = 0;
                long progress = resumePosition;
                byte[] buffer = new byte[4096 * 2];
                while ((read = is.read(buffer)) > 0 && !(interrupted = Thread.interrupted())) {
                    try {
                        fos.write(buffer, 0, read);
                    } catch (Exception e) {
                        msg = "磁盤空間已滿,無法下載";
                        throw e;
                    }
                    progress += read;
                    callback.onProgress(progress, fileLength);
                }
            } finally {
                IOUtil.closeQuietly(fos);
                IOUtil.closeQuietly(is);
            }
            if (file.exists()) {
                //檢驗數據是否完整
                if (file.length() == fileLength + resumePosition) {
                    callback.onSuccess();
                    return;
                }
            }
        } catch (Exception e) {
            interrupted = interrupted || Thread.interrupted() || (e instanceof InterruptedIOException && !(e instanceof SocketTimeoutException));
            msg = "網絡異常,下載失敗";
            if (interrupted) { msg = "下載被中斷!"; }
            callback.onFailed(true, msg);
        } finally {
            disconnect(conn);
        }
    }
    static void disconnect(HttpURLConnection conn) {
        try {
            if (conn == null) return;
            conn.disconnect();
        } catch (Throwable e) { e.printStackTrace(); }
    }
    public static abstract class Callback {
        public void onStart() { }
        public void onProgress(long progress, long total) { }
        public void onSuccess() { }
        public void onFailed(boolean cancelled, String msg) { }
    }
    public boolean isWifiActive(Context ctx) {
        try {
            ConnectivityManager mgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = mgr.getActiveNetworkInfo();
            return (info != null) ? info.getType() == ConnectivityManager.TYPE_WIFI : false;
        } catch (Exception e) { return false; }
    }
    public void cancelAllTask() {
        try {
            if (mTasks != null) {
                for (String taskKey : mTasks.keySet()) {
                    mTasks.get(taskKey).cancel();
                }
            }
        } catch (Exception e) { CommonUtil.printStackTrace(e); }
    }
    public void cancelTask(String key) {
        try {
            if (mTasks != null) { mTasks.get(key).cancel(); }
        } catch (Exception e) { CommonUtil.printStackTrace(e); }
    }
    public static boolean checkNetAvailable(Context ctx) {
        try {
            ConnectivityManager mgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = mgr.getActiveNetworkInfo();
            return (info != null) ? true : false;
        } catch (Exception e) { return true; }
    }
}

整段下載邏輯的精華,就在 runResumable 方法裡。它先取出已存在文件的長度作為 resumePosition,再在請求頭中設置 Range: bytes=起始位置-,服務器便會從該位置繼續返回數據,寫入時用 new FileOutputStream(file, true) 開啟追加模式即可。同時配合 416(範圍越界,說明已下載完)與 206(部分内容)狀態碼判斷,並在下載結束後校驗文件總長度是否等於「本次數據 + 斷點位置」,從而確保文件完整。若想更嚴謹,還可以用 MD5 對下載結果做校驗,代碼中也已註釋保留了相應位置。

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