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

OKHttp3 實現檔案下載:斷點續傳與進度顯示完整實作

編輯:關於 Android 程式設計

OKHttp3 是目前相當主流的 Android 網路請求框架,那要怎麼用它做斷點續傳?本文寫了一個 Demo 實測,把整個思路與程式碼記錄下來。

一、準備階段

技術組合是:OKHttp3 負責網路請求,RxJava 負責切換執行緒,並開啟 Java 8 以使用 Lambda 寫法。RxJava 做執行緒切換非常方便,搭配 Lambda 程式碼也更精簡。

在 app 模組的 build.gradle 中開啟 Java 8 並加入相依:

 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' } 

二、佈局檔

畫面上放三組「進度條+下載鈕+取消鈕」,方便同時展示多個下載任務:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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" /> <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" /> <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" /> <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> 

要說明的是:對下載而言「暫停」與「取消」在本例中並無區別,除非取消時順手把暫存檔也刪掉。這裡兩者一視同仁。

三、自訂 Application 取得全域 Context

下載需要用到檔案路徑,有一個全域 Context 會方便很多。Application 本身就是 Context 的子類,最適合拿來做這件事:

 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; } } 

別忘了在 Manifest 中註冊並補上網路權限:

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://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> 

四、核心: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; } } 

程式碼有點長,挑關鍵部分來看。

為什麼是單例

整個 App 只需要一個 OkHttpClient 就夠,所以把建構子設為私有,對外只開 getInstance()。同時在裡面初始化一個 HashMap 存放所有進行中的 Call,取消下載時就能依 url 找到對應請求並取消。

回呼用的 Observer

因為使用 RxJava 且沒有太多複雜分支,這裡直接寫一個抽象 Observer 當回呼,不必另開介面:

 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,參數正是用來取消訂閱的 Disposable,讓監聽者能自行決定何時停止接收。進度資訊會不斷從 onNext 送出。

下載資訊的載體

 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 是目前已下載量,兩者相除就能算出百分比。

download 方法的資料流

先用 url 建立 Observable,接著 filter 過濾掉「同一個 url 正在下載中」的情況;然後 createDownInfo 建立 DownloadInfo,其中會呼叫 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; } 

本質上就是發一次請求,從回應標頭讀出檔案大小。這個資訊通常拿得到,除非下載網址不是直接指向檔案,而是後端自己寫的程式輸出,那種情況就得跟後端確認有沒有帶 Content-Length。注意這次請求只問大小,不真的下載內容,原因後面會說明。

檢查本地已下載的部分

 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)」這種新名字重新下一份;若本地比伺服器小,代表上次下到一半斷了,那就把已下載量寫進 progress,稍後從這裡續傳。

真正的下載動作

 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();//完成 } } 

斷點續傳的關鍵就在這一行標頭:

 .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength) 

它告訴伺服器要抓的位元組範圍,讓對端跳過已經下載好的部分。少了這個標頭,就算你把輸入流跳過幾個位元組也沒用,因為伺服器仍會從頭傳。這也解釋了為什麼前面要多做一次請求:必須先知道總長度,才能判斷本地是否已有半截資料並組出正確的 Range。

寫檔這裡網上常見用 RandomAccessFile,但如果不涉及多段拼接,其實不必要。直接用 FileOutputStream 並在建構時帶入 true(附加模式)即可,迴圈中每寫一段就呼叫 onNext 送出最新進度,寫完關流並把 Call 從 HashMap 移除。關流統一交給這個小工具:

 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 裡用 observeOn / subscribeOn 把回呼切回主執行緒、下載本身放在 IO 執行緒,再 subscribe 我們的 Observer,整條鏈就串起來了。

五、Activity 端

 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 = "https://192.168.31.169:8080/out/dream.flac"; private String url2 = "https://192.168.31.169:8080/out/music.mp3"; private String url3 = "https://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 端就是綁定監聽、啟動下載、取消下載,沒有太多邏輯。實際跑起來:

可以看到多任務下載、進度更新與斷點續傳都正常運作。最後提醒兩點:範例中的網址指向作者自己的區網服務,請替換成你的測試位址;另外正式專案要在 onDestroy 中 dispose 掉 Disposable,避免 Activity 銷毀後仍回呼造成記憶體洩漏。

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