欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Android使用OKHttp3實(shí)現(xiàn)下載(斷點(diǎn)續(xù)傳、顯示進(jìn)度)

 更新時(shí)間:2017年02月03日 11:26:23   作者:藍(lán)牙鼠標(biāo)  
本篇文章主要介紹了詳解Android使用OKHttp3實(shí)現(xiàn)下載(斷點(diǎn)續(xù)傳、顯示進(jìn)度),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

OKHttp3是如今非常流行的Android網(wǎng)絡(luò)請(qǐng)求框架,那么如何利用Android實(shí)現(xiàn)斷點(diǎn)續(xù)傳呢,今天寫了個(gè)Demo嘗試了一下,感覺還是有點(diǎn)意思

準(zhǔn)備階段

我們會(huì)用到OKHttp3來做網(wǎng)絡(luò)請(qǐng)求,使用RxJava來實(shí)現(xiàn)線程的切換,并且開啟Java8來啟用Lambda表達(dá)式,畢竟RxJava實(shí)現(xiàn)線程切換非常方便,而且數(shù)據(jù)流的形式也非常舒服,同時(shí)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表達(dá)式 
  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> 

大概是這個(gè)樣子的

3個(gè)ProgressBar就是為了顯示進(jìn)度的,每個(gè)ProgressBar對(duì)應(yīng)2個(gè)Button,一個(gè)是開始下載,一個(gè)是暫停(取消)下載,這里需要說明的是,對(duì)下載來說暫停和取消沒有什么區(qū)別,除非當(dāng)取消的時(shí)候,會(huì)順帶把臨時(shí)文件都刪除了,在本例里是不區(qū)分他倆的.

Application

我們這里需要用到一些文件路徑,有一個(gè)全局Context會(huì)比較方便, 而Application也是Context的子類,使用它的是最方便的,所以我們寫一個(gè)類來繼承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對(duì)象 
 
  @Override 
  public void onCreate() { 
    super.onCreate(); 
    sContext = this; 
  } 
} 

可以看到,我們就是要獲得一個(gè)全局的Context對(duì)象的

我們?cè)贏ndroidManifest中注冊(cè)一下我們的Application,同時(shí)再把我們所需要的權(quán)限給上

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  package="com.lanou3g.downdemo"> 
   
  <!--網(wǎng)絡(luò)權(quán)限--> 
  <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> 

我們只需要一個(gè)網(wǎng)絡(luò)權(quán)限,在application標(biāo)簽下,添加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;//用來存放各個(gè)下載的請(qǐng)求 
  private OkHttpClient mClient;//OKHttpClient; 
 
  //獲得一個(gè)單例類 
  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       下載請(qǐng)求的網(wǎng)址 
   * @param downLoadObserver 用來回調(diào)的接口 
   */ 
  public void download(String url, DownLoadObserver downLoadObserver) { 
    Observable.just(url) 
        .filter(s -> !downCalls.containsKey(s))//call的map已經(jīng)有了,就證明正在下載,則這次不下載 
        .flatMap(s -> Observable.just(createDownInfo(s))) 
        .map(this::getRealFileName)//檢測(cè)本地文件夾,生成新的文件名 
        .flatMap(downloadInfo -> Observable.create(new DownloadSubscribe(downloadInfo)))//下載 
        .observeOn(AndroidSchedulers.mainThread())//在主線程回調(diào) 
        .subscribeOn(Schedulers.io())//在子線程執(zhí)行 
        .subscribe(downLoadObserver);//添加觀察者 
 
  } 
 
  public void cancel(String url) { 
    Call call = downCalls.get(url); 
    if (call != null) { 
      call.cancel();//取消 
    } 
    downCalls.remove(url); 
  } 
 
  /** 
   * 創(chuàng)建DownInfo 
   * 
   * @param url 請(qǐng)求網(wǎng)址 
   * @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()) { 
      //找到了文件,代表已經(jīng)下載過,則獲取其長(zhǎng)度 
      downloadLength = file.length(); 
    } 
    //之前下載過,需要重新來一個(gè)文件 
    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++; 
    } 
    //設(shè)置改變過的文件名/大小 
    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();//已經(jīng)下載好的長(zhǎng)度 
      long contentLength = downloadInfo.getTotal();//文件的總長(zhǎng)度 
      //初始進(jìn)度信息 
      e.onNext(downloadInfo); 
 
      Request request = new Request.Builder() 
          //確定下載的范圍,添加此頭,則服務(wù)器就可以跳過已經(jīng)下載好的部分 
          .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength) 
          .url(url) 
          .build(); 
      Call call = mClient.newCall(request); 
      downCalls.put(url, call);//把這個(gè)添加到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];//緩沖數(shù)組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 { 
        //關(guān)閉IO流 
        IOUtil.closeAll(is, fileOutputStream); 
 
      } 
      e.onComplete();//完成 
    } 
  } 
 
  /** 
   * 獲取下載長(zhǎng)度 
   * 
   * @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; 
  } 
 
 
} 

代碼稍微有點(diǎn)長(zhǎng),關(guān)鍵部位我都加了注釋了,我們挑關(guān)鍵地方看看

首先我們這個(gè)類是單例類,我們下載只需要一個(gè)OKHttpClient就足夠了,所以我們讓構(gòu)造方法私有,而單例類的獲取實(shí)例方法就是這個(gè)getInstance();當(dāng)然大家用別的方式實(shí)現(xiàn)單例也可以的,然后我們?cè)跇?gòu)造方法里初始化我們的HttpClient,并且初始化一個(gè)HashMap,用來放所有的網(wǎng)絡(luò)請(qǐng)求的,這樣當(dāng)我們?nèi)∠螺d的時(shí)候,就可以找到url對(duì)應(yīng)的網(wǎng)絡(luò)請(qǐng)求然后把它取消掉就可以了

接下來就是核心的download方法了,首先是參數(shù),第一個(gè)參數(shù)url不用多說,就是請(qǐng)求的網(wǎng)址,第二個(gè)參數(shù)是一個(gè)Observer對(duì)象,因?yàn)槲覀兪褂玫氖荝xJava,并且沒有特別多復(fù)雜的方法,所以就沒單獨(dú)寫接口,而是謝了一個(gè)Observer對(duì)象來作為回調(diào),接下來是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;//可以用于取消注冊(cè)的監(jiān)聽者 
  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中 這個(gè)Observer有點(diǎn)變化,當(dāng)注冊(cè)觀察者的時(shí)候,會(huì)調(diào)用onSubscribe方法,而該方法參數(shù)就是用來取消注冊(cè)的,這樣的改動(dòng)可以更靈活的有監(jiān)聽者來取消監(jiān)聽了,我們的進(jìn)度信息會(huì)一直的傳送的onNext方法里,這里將下載所需要的內(nèi)容封了一個(gè)類叫DownloadInfo

package com.lanou3g.downdemo; 
 
/** 
 * Created by 陳豐堯 on 2017/2/2. 
 * 下載信息 
 */ 
 
public class DownloadInfo { 
  public static final long TOTAL_ERROR = -1;//獲取進(jìn)度失敗 
  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; 
  } 
} 

這個(gè)類就是一些基本信息,total就是需要下載的文件的總大小,而progress就是當(dāng)前下載的進(jìn)度了,這樣就可以計(jì)算出下載的進(jìn)度信息了

接著看DownloadManager的download方法,首先通過url生成一個(gè)Observable對(duì)象,然后通過filter操作符過濾一下,如果當(dāng)前正在下載這個(gè)url對(duì)應(yīng)的內(nèi)容,那么就不下載它,

接下來調(diào)用createDownInfo重新生成Observable對(duì)象,這里應(yīng)該用map也是可以的,createDownInfo這個(gè)方法里會(huì)調(diào)用getContentLength來獲取服務(wù)器上的文件大小,可以看一下這個(gè)方法的代碼,

/** 
  * 獲取下載長(zhǎng)度 
  * 
  * @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; 
  } 

可以看到,其實(shí)就是在通過OK進(jìn)行了一次網(wǎng)絡(luò)請(qǐng)求,并且從返回的頭信息里拿到文件的大小信息,一般這個(gè)信息都是可以拿到的,除非下載網(wǎng)址不是直接指向資源文件的,而是自己手寫的Servlet,那就得跟后臺(tái)人員溝通好了.注意,這次網(wǎng)絡(luò)請(qǐng)求并沒有真正的去下載文件,而是請(qǐng)求個(gè)大小就結(jié)束了,具體原因會(huì)在后面真正請(qǐng)求數(shù)據(jù)的時(shí)候解釋

接著download方法

獲取完文件大小后,就可以去硬盤里找文件了,這里調(diào)用了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()) { 
      //找到了文件,代表已經(jīng)下載過,則獲取其長(zhǎng)度 
      downloadLength = file.length(); 
    } 
    //之前下載過,需要重新來一個(gè)文件 
    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++; 
    } 
    //設(shè)置改變過的文件名/大小 
    downloadInfo.setProgress(downloadLength); 
    downloadInfo.setFileName(file.getName()); 
    return downloadInfo; 
  } 

這個(gè)方法就是看本地是否有已經(jīng)下載過的文件,如果有,再判斷一次本地文件的大小和服務(wù)器上數(shù)據(jù)的大小,如果是一樣的,證明之前下載全了,就再成一個(gè)帶(1)這樣的文件,而如果本地文件大小比服務(wù)器上的小的話,那么證明之前下載了一半斷掉了,那么就把進(jìn)度信息保存上,并把文件名也存上,看完了再回到download方法

之后就開始真正的網(wǎng)絡(luò)請(qǐng)求了,這里寫了一個(gè)內(nèi)部類來實(shí)現(xiàn)ObservableOnSubscribe接口,這個(gè)接口也是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();//已經(jīng)下載好的長(zhǎng)度 
      long contentLength = downloadInfo.getTotal();//文件的總長(zhǎng)度 
      //初始進(jìn)度信息 
      e.onNext(downloadInfo); 
 
      Request request = new Request.Builder() 
          //確定下載的范圍,添加此頭,則服務(wù)器就可以跳過已經(jīng)下載好的部分 
          .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength) 
          .url(url) 
          .build(); 
      Call call = mClient.newCall(request); 
      downCalls.put(url, call);//把這個(gè)添加到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];//緩沖數(shù)組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 { 
        //關(guān)閉IO流 
        IOUtil.closeAll(is, fileOutputStream); 
 
      } 
      e.onComplete();//完成 
    } 
  } 

主要看subscribe方法

首先拿到url,當(dāng)前進(jìn)度信息和文件的總大小,然后開始網(wǎng)絡(luò)請(qǐng)求,注意這次網(wǎng)絡(luò)請(qǐng)求的時(shí)候需要添加一條頭信息

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

這條頭信息的意思是下載的范圍是多少,downloadLength是從哪開始下載,contentLength是下載到哪,當(dāng)要斷點(diǎn)續(xù)傳的話必須添加這個(gè)頭,讓輸入流跳過多少字節(jié)的形式是不行的,所以我們要想能成功的添加這條信息那么就必須對(duì)這個(gè)url請(qǐng)求2次,一次拿到總長(zhǎng)度,來方便判斷本地是否有下載一半的數(shù)據(jù),第二次才開始真正的讀流進(jìn)行網(wǎng)絡(luò)請(qǐng)求,我還想了一種思路,當(dāng)文件沒有下載完成的時(shí)候添加一個(gè)自定義的后綴,當(dāng)下載完成再把這個(gè)后綴取消了,應(yīng)該就不需要請(qǐng)求兩次了.

接下來就是正常的網(wǎng)絡(luò)請(qǐng)求,向本地寫文件了,而寫文件到本地這,網(wǎng)上大多用的是RandomAccessFile這個(gè)類,但是如果不涉及到多個(gè)部分拼接的話是沒必要的,直接使用輸出流就好了,在輸出流的構(gòu)造方法上添加一個(gè)true的參數(shù),代表是在原文件的后面添加數(shù)據(jù)即可,而在循環(huán)里,不斷的調(diào)用onNext方法發(fā)送進(jìn)度信息,當(dāng)寫完了之后別忘了關(guān)流,同時(shí)把call對(duì)象從hashMap中移除了.這里寫了一個(gè)IOUtil來關(guān)流

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

其實(shí)就是挨一個(gè)判斷是否為空,并關(guān)閉罷了

這樣download方法就完成了,剩下的就是切換線程,注冊(cè)觀察者了

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里沒什么了,就是注冊(cè)監(jiān)聽,開始下載,取消下載這些了,下面我們來看看效果吧

運(yùn)行效果

可以看到 多個(gè)下載,斷點(diǎn)續(xù)傳什么的都已經(jīng)成功了,最后我的文件網(wǎng)址是我自己的局域網(wǎng),大家寫的時(shí)候別忘了換了..

代碼地址:demo

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論