1. 程式人生 > >Android使用OKHttp3實現下載(斷點續傳、顯示進度)

Android使用OKHttp3實現下載(斷點續傳、顯示進度)

OKHttp3是如今非常流行的Android網路請求框架,那麼如何利用Android實現斷點續傳呢,今天寫了個Demo嘗試了一下,感覺還是有點意思

準備階段

我們會用到OKHttp3來做網路請求,使用RxJava來實現執行緒的切換,並且開啟Java8來啟用Lambda表示式,畢竟RxJava實現執行緒切換非常方便,而且資料流的形式也非常舒服,同時Lambda和RxJava配合食用味道更佳

開啟我們的app Module下的build.gradle,程式碼如下

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"

    defaultConfig {
        applicationId "com.lanou3g.downdemo"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        //為了開啟Java8
        jackOptions{
            enabled true;
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    //開啟Java1.8 能夠使用lambda表示式
    compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.1.1'
    testCompile 'junit:junit:4.12'

    //OKHttp
    compile 'com.squareup.okhttp3:okhttp:3.6.0'
    //RxJava和RxAndroid 用來做執行緒切換的
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
}
OKHttp和RxJava,RxAndroid使用的都是最新的版本,並且配置開啟了Java8

佈局檔案

接著開始書寫佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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"
    android:orientation="vertical"
    tools:context="com.lanou3g.downdemo.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ProgressBar
            android:id="@+id/main_progress1"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal" />
        <Button
            android:id="@+id/main_btn_down1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="下載1"/>
        <Button
            android:id="@+id/main_btn_cancel1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="取消1"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ProgressBar
            android:id="@+id/main_progress2"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal" />
        <Button
            android:id="@+id/main_btn_down2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="下載2"/>
        <Button
            android:id="@+id/main_btn_cancel2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="取消2"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ProgressBar
            android:id="@+id/main_progress3"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            style="@style/Widget.AppCompat.ProgressBar.Horizontal" />
        <Button
            android:id="@+id/main_btn_down3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="下載3"/>
        <Button
            android:id="@+id/main_btn_cancel3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="取消3"/>
    </LinearLayout>
</LinearLayout>
大概是這個樣子的


3個ProgressBar就是為了顯示進度的,每個ProgressBar對應2個Button,一個是開始下載,一個是暫停(取消)下載,這裡需要說明的是,對下載來說暫停和取消沒有什麼區別,除非當取消的時候,會順帶把臨時檔案都刪除了,在本例裡是不區分他倆的.

Application

我們這裡需要用到一些檔案路徑,有一個全域性Context會比較方便, 而Application也是Context的子類,使用它的是最方便的,所以我們寫一個類來繼承Application
package com.lanou3g.downdemo;

import android.app.Application;
import android.content.Context;

/**
 * Created by 陳豐堯 on 2017/2/2.
 */

public class MyApp extends Application {
    public static Context sContext;//全域性的Context物件

    @Override
    public void onCreate() {
        super.onCreate();
        sContext = this;
    }
}
可以看到,我們就是要獲得一個全域性的Context物件的 我們在AndroidManifest中註冊一下我們的Application,同時再把我們所需要的許可權給上
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lanou3g.downdemo">
    
    <!--網路許可權-->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:name=".MyApp"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
我們只需要一個網路許可權,在application標籤下,新增name屬性,來指向我們的Application

DownloadManager

接下來是核心程式碼了,就是我們的DownloadManager,先上程式碼
package com.lanou3g.downdemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicReference;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 陳豐堯 on 2017/2/2.
 */

public class DownloadManager {

    private static final AtomicReference<DownloadManager> INSTANCE = new AtomicReference<>();
    private HashMap<String, Call> downCalls;//用來存放各個下載的請求
    private OkHttpClient mClient;//OKHttpClient;

    //獲得一個單例類
    public static DownloadManager getInstance() {
        for (; ; ) {
            DownloadManager current = INSTANCE.get();
            if (current != null) {
                return current;
            }
            current = new DownloadManager();
            if (INSTANCE.compareAndSet(null, current)) {
                return current;
            }
        }
    }

    private DownloadManager() {
        downCalls = new HashMap<>();
        mClient = new OkHttpClient.Builder().build();
    }

    /**
     * 開始下載
     *
     * @param url              下載請求的網址
     * @param downLoadObserver 用來回調的介面
     */
    public void download(String url, DownLoadObserver downLoadObserver) {
        Observable.just(url)
                .filter(s -> !downCalls.containsKey(s))//call的map已經有了,就證明正在下載,則這次不下載
                .flatMap(s -> Observable.just(createDownInfo(s)))
                .map(this::getRealFileName)//檢測本地資料夾,生成新的檔名
                .flatMap(downloadInfo -> Observable.create(new DownloadSubscribe(downloadInfo)))//下載
                .observeOn(AndroidSchedulers.mainThread())//在主執行緒回撥
                .subscribeOn(Schedulers.io())//在子執行緒執行
                .subscribe(downLoadObserver);//新增觀察者

    }

    public void cancel(String url) {
        Call call = downCalls.get(url);
        if (call != null) {
            call.cancel();//取消
        }
        downCalls.remove(url);
    }

    /**
     * 建立DownInfo
     *
     * @param url 請求網址
     * @return DownInfo
     */
    private DownloadInfo createDownInfo(String url) {
        DownloadInfo downloadInfo = new DownloadInfo(url);
        long contentLength = getContentLength(url);//獲得檔案大小
        downloadInfo.setTotal(contentLength);
        String fileName = url.substring(url.lastIndexOf("/"));
        downloadInfo.setFileName(fileName);
        return downloadInfo;
    }

    private DownloadInfo getRealFileName(DownloadInfo downloadInfo) {
        String fileName = downloadInfo.getFileName();
        long downloadLength = 0, contentLength = downloadInfo.getTotal();
        File file = new File(MyApp.sContext.getFilesDir(), fileName);
        if (file.exists()) {
            //找到了檔案,代表已經下載過,則獲取其長度
            downloadLength = file.length();
        }
        //之前下載過,需要重新來一個檔案
        int i = 1;
        while (downloadLength >= contentLength) {
            int dotIndex = fileName.lastIndexOf(".");
            String fileNameOther;
            if (dotIndex == -1) {
                fileNameOther = fileName + "(" + i + ")";
            } else {
                fileNameOther = fileName.substring(0, dotIndex)
                        + "(" + i + ")" + fileName.substring(dotIndex);
            }
            File newFile = new File(MyApp.sContext.getFilesDir(), fileNameOther);
            file = newFile;
            downloadLength = newFile.length();
            i++;
        }
        //設定改變過的檔名/大小
        downloadInfo.setProgress(downloadLength);
        downloadInfo.setFileName(file.getName());
        return downloadInfo;
    }

    private class DownloadSubscribe implements ObservableOnSubscribe<DownloadInfo> {
        private DownloadInfo downloadInfo;

        public DownloadSubscribe(DownloadInfo downloadInfo) {
            this.downloadInfo = downloadInfo;
        }

        @Override
        public void subscribe(ObservableEmitter<DownloadInfo> e) throws Exception {
            String url = downloadInfo.getUrl();
            long downloadLength = downloadInfo.getProgress();//已經下載好的長度
            long contentLength = downloadInfo.getTotal();//檔案的總長度
            //初始進度資訊
            e.onNext(downloadInfo);

            Request request = new Request.Builder()
                    //確定下載的範圍,新增此頭,則伺服器就可以跳過已經下載好的部分
                    .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength)
                    .url(url)
                    .build();
            Call call = mClient.newCall(request);
            downCalls.put(url, call);//把這個新增到call裡,方便取消
            Response response = call.execute();

            File file = new File(MyApp.sContext.getFilesDir(), downloadInfo.getFileName());
            InputStream is = null;
            FileOutputStream fileOutputStream = null;
            try {
                is = response.body().byteStream();
                fileOutputStream = new FileOutputStream(file, true);
                byte[] buffer = new byte[2048];//緩衝陣列2kB
                int len;
                while ((len = is.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                    downloadLength += len;
                    downloadInfo.setProgress(downloadLength);
                    e.onNext(downloadInfo);
                }
                fileOutputStream.flush();
                downCalls.remove(url);
            } finally {
                //關閉IO流
                IOUtil.closeAll(is, fileOutputStream);

            }
            e.onComplete();//完成
        }
    }

    /**
     * 獲取下載長度
     *
     * @param downloadUrl
     * @return
     */
    private long getContentLength(String downloadUrl) {
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response != null && response.isSuccessful()) {
                long contentLength = response.body().contentLength();
                response.close();
                return contentLength == 0 ? DownloadInfo.TOTAL_ERROR : contentLength;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DownloadInfo.TOTAL_ERROR;
    }


}


程式碼稍微有點長,關鍵部位我都加了註釋了,我們挑關鍵地方看看 首先我們這個類是單例類,我們下載只需要一個OKHttpClient就足夠了,所以我們讓構造方法私有,而單例類的獲取例項方法就是這個getInstance();當然大家用別的方式實現單例也可以的,然後我們在構造方法裡初始化我們的HttpClient,並且初始化一個HashMap,用來放所有的網路請求的,這樣當我們取消下載的時候,就可以找到url對應的網路請求然後把它取消掉就可以了 接下來就是核心的download方法了,首先是引數,第一個引數url不用多說,就是請求的網址,第二個引數是一個Observer物件,因為我們使用的是RxJava,並且沒有特別多複雜的方法,所以就沒單獨寫介面,而是謝了一個Observer物件來作為回撥,接下來是DownLoadObserver的程式碼
package com.lanou3g.downdemo;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by 陳豐堯 on 2017/2/2.
 */

public  abstract class DownLoadObserver implements Observer<DownloadInfo> {
    protected Disposable d;//可以用於取消註冊的監聽者
    protected DownloadInfo downloadInfo;
    @Override
    public void onSubscribe(Disposable d) {
        this.d = d;
    }

    @Override
    public void onNext(DownloadInfo downloadInfo) {
        this.downloadInfo = downloadInfo;
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
    }


}
在RxJava2中 這個Observer有點變化,當註冊觀察者的時候,會呼叫onSubscribe方法,而該方法引數就是用來取消註冊的,這樣的改動可以更靈活的有監聽者來取消監聽了,我們的進度資訊會一直的傳送的onNext方法裡,這裡將下載所需要的內容封了一個類叫DownloadInfo
package com.lanou3g.downdemo;

/**
 * Created by 陳豐堯 on 2017/2/2.
 * 下載資訊
 */

public class DownloadInfo {
    public static final long TOTAL_ERROR = -1;//獲取進度失敗
    private String url;
    private long total;
    private long progress;
    private String fileName;
    
    public DownloadInfo(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public long getProgress() {
        return progress;
    }

    public void setProgress(long progress) {
        this.progress = progress;
    }
}
這個類就是一些基本資訊,total就是需要下載的檔案的總大小,而progress就是當前下載的進度了,這樣就可以計算出下載的進度資訊了 接著看DownloadManager的download方法,首先通過url生成一個Observable物件,然後通過filter操作符過濾一下,如果當前正在下載這個url對應的內容,那麼就不下載它, 接下來呼叫createDownInfo重新生成Observable物件,這裡應該用map也是可以的,createDownInfo這個方法裡會呼叫getContentLength來獲取伺服器上的檔案大小,可以看一下這個方法的程式碼,
 /**
     * 獲取下載長度
     *
     * @param downloadUrl
     * @return
     */
    private long getContentLength(String downloadUrl) {
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        try {
            Response response = mClient.newCall(request).execute();
            if (response != null && response.isSuccessful()) {
                long contentLength = response.body().contentLength();
                response.close();
                return contentLength == 0 ? DownloadInfo.TOTAL_ERROR : contentLength;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DownloadInfo.TOTAL_ERROR;
    }
可以看到,其實就是在通過OK進行了一次網路請求,並且從返回的頭資訊裡拿到檔案的大小資訊,一般這個資訊都是可以拿到的,除非下載網址不是直接指向資原始檔的,而是自己手寫的Servlet,那就得跟後臺人員溝通好了.注意,這次網路請求並沒有真正的去下載檔案,而是請求個大小就結束了,具體原因會在後面真正請求資料的時候解釋 接著download方法

獲取完檔案大小後,就可以去硬盤裡找檔案了,這裡呼叫了getRealFileName方法

private DownloadInfo getRealFileName(DownloadInfo downloadInfo) {
        String fileName = downloadInfo.getFileName();
        long downloadLength = 0, contentLength = downloadInfo.getTotal();
        File file = new File(MyApp.sContext.getFilesDir(), fileName);
        if (file.exists()) {
            //找到了檔案,代表已經下載過,則獲取其長度
            downloadLength = file.length();
        }
        //之前下載過,需要重新來一個檔案
        int i = 1;
        while (downloadLength >= contentLength) {
            int dotIndex = fileName.lastIndexOf(".");
            String fileNameOther;
            if (dotIndex == -1) {
                fileNameOther = fileName + "(" + i + ")";
            } else {
                fileNameOther = fileName.substring(0, dotIndex)
                        + "(" + i + ")" + fileName.substring(dotIndex);
            }
            File newFile = new File(MyApp.sContext.getFilesDir(), fileNameOther);
            file = newFile;
            downloadLength = newFile.length();
            i++;
        }
        //設定改變過的檔名/大小
        downloadInfo.setProgress(downloadLength);
        downloadInfo.setFileName(file.getName());
        return downloadInfo;
    }
這個方法就是看本地是否有已經下載過的檔案,如果有,再判斷一次本地檔案的大小和伺服器上資料的大小,如果是一樣的,證明之前下載全了,就再成一個帶(1)這樣的檔案,而如果本地檔案大小比伺服器上的小的話,那麼證明之前下載了一半斷掉了,那麼就把進度資訊儲存上,並把檔名也存上,看完了再回到download方法

之後就開始真正的網路請求了,這裡寫了一個內部類來實現ObservableOnSubscribe介面,這個介面也是RxJava2的,東西和之前一樣,好像只改了名字,看一下程式碼

private class DownloadSubscribe implements ObservableOnSubscribe<DownloadInfo> {
        private DownloadInfo downloadInfo;

        public DownloadSubscribe(DownloadInfo downloadInfo) {
            this.downloadInfo = downloadInfo;
        }

        @Override
        public void subscribe(ObservableEmitter<DownloadInfo> e) throws Exception {
            String url = downloadInfo.getUrl();
            long downloadLength = downloadInfo.getProgress();//已經下載好的長度
            long contentLength = downloadInfo.getTotal();//檔案的總長度
            //初始進度資訊
            e.onNext(downloadInfo);

            Request request = new Request.Builder()
                    //確定下載的範圍,新增此頭,則伺服器就可以跳過已經下載好的部分
                    .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength)
                    .url(url)
                    .build();
            Call call = mClient.newCall(request);
            downCalls.put(url, call);//把這個新增到call裡,方便取消
            Response response = call.execute();

            File file = new File(MyApp.sContext.getFilesDir(), downloadInfo.getFileName());
            InputStream is = null;
            FileOutputStream fileOutputStream = null;
            try {
                is = response.body().byteStream();
                fileOutputStream = new FileOutputStream(file, true);
                byte[] buffer = new byte[2048];//緩衝陣列2kB
                int len;
                while ((len = is.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                    downloadLength += len;
                    downloadInfo.setProgress(downloadLength);
                    e.onNext(downloadInfo);
                }
                fileOutputStream.flush();
                downCalls.remove(url);
            } finally {
                //關閉IO流
                IOUtil.closeAll(is, fileOutputStream);

            }
            e.onComplete();//完成
        }
    }
主要看subscribe方法

首先拿到url,當前進度資訊和檔案的總大小,然後開始網路請求,注意這次網路請求的時候需要新增一條頭資訊

.addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength)
這條頭資訊的意思是下載的範圍是多少,downloadLength是從哪開始下載,contentLength是下載到哪,當要斷點續傳的話必須新增這個頭,讓輸入流跳過多少位元組的形式是不行的,所以我們要想能成功的新增這條資訊那麼就必須對這個url請求2次,一次拿到總長度,來方便判斷本地是否有下載一半的資料,第二次才開始真正的讀流進行網路請求,我還想了一種思路,當檔案沒有下載完成的時候新增一個自定義的字尾,當下載完成再把這個字尾取消了,應該就不需要請求兩次了.

接下來就是正常的網路請求,向本地寫檔案了,而寫檔案到本地這,網上大多用的是RandomAccessFile這個類,但是如果不涉及到多個部分拼接的話是沒必要的,直接使用輸出流就好了,在輸出流的構造方法上新增一個true的引數,代表是在原檔案的後面新增資料即可,而在迴圈裡,不斷的呼叫onNext方法傳送進度資訊,當寫完了之後別忘了關流,同時把call物件從hashMap中移除了.這裡寫了一個IOUtil來關流

package com.lanou3g.downdemo;

import java.io.Closeable;
import java.io.IOException;

/**
 * Created by 陳豐堯 on 2017/2/2.
 */

public class IOUtil {
    public static void closeAll(Closeable... closeables){
        if(closeables == null){
            return;
        }
        for (Closeable closeable : closeables) {
            if(closeable!=null){
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
其實就是挨一個判斷是否為空,並關閉罷了

這樣download方法就完成了,剩下的就是切換執行緒,註冊觀察者了

MainActivity

最後是aty的程式碼
package com.lanou3g.downdemo;

import android.net.Uri;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button downloadBtn1, downloadBtn2, downloadBtn3;
    private Button cancelBtn1, cancelBtn2, cancelBtn3;
    private ProgressBar progress1, progress2, progress3;
    private String url1 = "http://192.168.31.169:8080/out/dream.flac";
    private String url2 = "http://192.168.31.169:8080/out/music.mp3";
    private String url3 = "http://192.168.31.169:8080/out/code.zip";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadBtn1 = bindView(R.id.main_btn_down1);
        downloadBtn2 = bindView(R.id.main_btn_down2);
        downloadBtn3 = bindView(R.id.main_btn_down3);

        cancelBtn1 = bindView(R.id.main_btn_cancel1);
        cancelBtn2 = bindView(R.id.main_btn_cancel2);
        cancelBtn3 = bindView(R.id.main_btn_cancel3);

        progress1 = bindView(R.id.main_progress1);
        progress2 = bindView(R.id.main_progress2);
        progress3 = bindView(R.id.main_progress3);

        downloadBtn1.setOnClickListener(this);
        downloadBtn2.setOnClickListener(this);
        downloadBtn3.setOnClickListener(this);

        cancelBtn1.setOnClickListener(this);
        cancelBtn2.setOnClickListener(this);
        cancelBtn3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_btn_down1:
                DownloadManager.getInstance().download(url1, new DownLoadObserver() {
                    @Override
                    public void onNext(DownloadInfo value) {
                        super.onNext(value);
                        progress1.setMax((int) value.getTotal());
                        progress1.setProgress((int) value.getProgress());
                    }

                    @Override
                    public void onComplete() {
                        if(downloadInfo != null){
                            Toast.makeText(MainActivity.this,
                                    downloadInfo.getFileName() + "-DownloadComplete",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                break;
            case R.id.main_btn_down2:
                DownloadManager.getInstance().download(url2, new DownLoadObserver() {
                    @Override
                    public void onNext(DownloadInfo value) {
                        super.onNext(value);
                        progress2.setMax((int) value.getTotal());
                        progress2.setProgress((int) value.getProgress());
                    }

                    @Override
                    public void onComplete() {
                        if(downloadInfo != null){
                            Toast.makeText(MainActivity.this,
                                    downloadInfo.getFileName() + Uri.encode("下載完成"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                break;
            case R.id.main_btn_down3:
                DownloadManager.getInstance().download(url3, new DownLoadObserver() {
                    @Override
                    public void onNext(DownloadInfo value) {
                        super.onNext(value);
                        progress3.setMax((int) value.getTotal());
                        progress3.setProgress((int) value.getProgress());
                    }

                    @Override
                    public void onComplete() {
                        if(downloadInfo != null){
                            Toast.makeText(MainActivity.this,
                                    downloadInfo.getFileName() + "下載完成",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                break;
            case R.id.main_btn_cancel1:
                DownloadManager.getInstance().cancel(url1);
                break;
            case R.id.main_btn_cancel2:
                DownloadManager.getInstance().cancel(url2);
                break;
            case R.id.main_btn_cancel3:
                DownloadManager.getInstance().cancel(url3);
                break;
        }
    }
    
    private <T extends View> T bindView(@IdRes int id){
        View viewById = findViewById(id);
        return (T) viewById;
    }
}
Activity裡沒什麼了,就是註冊監聽,開始下載,取消下載這些了,下面我們來看看效果吧

執行效果



可以看到 多個下載,斷點續傳什麼的都已經成功了,最後我的檔案網址是我自己的區域網,大家寫的時候別忘了換了..

程式碼 http://download.csdn.net/detail/cfy137000/9746583