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

RxJava2.x+ReTrofit2.x多線程下載文件的示例代碼

 更新時間:2017年09月18日 14:16:19   作者:ready_z  
本篇文章主要介紹了RxJava2.x+ReTrofit2.x多線程下載文件的示例代碼,具有一定的參考價值,有興趣的可以了解一下

寫在前面:

接到公司需求:要做一個apk升級的功能,原理其實很簡單,百度也一大堆例子,可大部分都是用框架,要么就是HttpURLConnection,實在是不想這么干。正好看了兩天的RxJava2.x+ReTrofit2.x,據(jù)說這倆框架是目前最火的異步請求框架了。固本文使用RxJava2.x+ReTrofit2.x實現(xiàn)多線程下載文件的功能。
如果對RxJava2.x+ReTrofit2.x不太了解的請先去看相關(guān)的文檔。
大神至此請無視。

思路分析:

思路及其簡潔明了,主要分為以下四步

1.獲取服務(wù)器文件大小.
2.根據(jù)文件大小規(guī)劃線程數(shù)量.
3.根據(jù)下載內(nèi)容合并為完整文件.
4.調(diào)用安裝,安裝apk.
功能實現(xiàn)

來,接下來是你們最喜歡的擼代碼環(huán)節(jié)

1.首先看引用

  compile 'io.reactivex:rxjava:latest.release'
  compile 'io.reactivex:rxandroid:latest.release'
  //network - squareup
  compile 'com.squareup.retrofit2:retrofit:latest.release'
  compile 'com.squareup.retrofit2:adapter-rxjava:latest.release'
  compile 'com.squareup.okhttp3:okhttp:latest.release'
  compile 'com.squareup.okhttp3:logging-interceptor:latest.release'

2.構(gòu)造一個下載接口DownloadService.class

public interface DownloadService {
  @Streaming
  @GET
  //downParam下載參數(shù),傳下載區(qū)間使用
  //url 下載鏈接
  Observable<ResponseBody> download(@Header("RANGE") String downParam,@Url String url);
}

3.為了使用方便封裝了一個RetrofitHelper.class,主要用于:

a)實例化OkHttpClient和Retrofit.

  public RetrofitHelper(String url, DownloadProgressListener listener) {

    DownloadProgressInterceptor interceptor = new DownloadProgressInterceptor(listener);

    OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(interceptor)
        .retryOnConnectionFailure(true)
        .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
        .build();
    retrofit = new Retrofit.Builder()
        .baseUrl(url)
        .client(client)
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();
  }

b)封裝下載方法,本次下載我使用的是三個下載線程,并沒有動態(tài)分配,各位可以根據(jù)自己的需求去動態(tài)分配線程個數(shù)

 public Observable download(@NonNull final long start, @NonNull final long end, @NonNull final String url, final File file, final Subscriber subscriber) {
    String str = "";
    if (end == -1) {
      str = "";
    } else {
      str = end + "";
    }
    return retrofit.create(DownloadService.class).download("bytes=" + start + "-" + str, url).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).map(new Func1<ResponseBody, ResponseBody>() {
      @Override
      public ResponseBody call(ResponseBody responseBody) {
        return responseBody;
      }
    }).observeOn(Schedulers.computation()).doOnNext(new Action1<ResponseBody>() {
      @Override
      public void call(ResponseBody responseBody) {
        //第一次請求全部文件長度
        if (end == -1) {
          try {
            RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
            randomFile.setLength(responseBody.contentLength());
            long one = responseBody.contentLength() / 3;
            download(0, one, url, file, subscriber).mergeWith(download(one, one * 2, url, file, subscriber)).mergeWith(download(one * 2, responseBody.contentLength(), url, file, subscriber)).subscribe(subscriber);

          } catch (IOException e) {
            e.printStackTrace();
          }
        } else {
          FileUtils fileUtils = new FileUtils();
          fileUtils.writeFile(start, end, responseBody.byteStream(), file);
        }

      }
    }).subscribeOn(AndroidSchedulers.mainThread());
  }

 4.調(diào)用下載

注:調(diào)用下載在MainAcitivity中進行,為了直觀我們封裝了進度攔截器以方便實現(xiàn)進度顯示,但是本篇不在敘述進度攔截器的實現(xiàn)過程,如有需要可以留言。

a)實現(xiàn)監(jiān)聽對象

subscriber = new Subscriber() {
      @Override
      public void onCompleted() {
        Log.e("MainActivity", "onCompleted下下載完成");
//        Toast.makeText(MainActivity.this, "onCompleted下下載完成", Toast.LENGTH_LONG).show();
        installAPK("mnt/sdcard/aaaaaaaaa.apk");
      }

      @Override
      public void onError(Throwable e) {
        e.printStackTrace();
        Log.e("MainActivity", "onError: " + e.getMessage());
      }

      @Override
      public void onNext(Object o) {

      }
    };

 b)調(diào)用封裝的RetrofitHelper實現(xiàn)下載

 RetrofitHelper RetrofitHelper = new RetrofitHelper("http://gdown.baidu.com/data/wisegame/0904344dee4a2d92/", new DownloadProgressListener() {
      @Override
      public void update(long bytesRead, long contentLength, boolean done) {

        SharedPF.getSharder().setLong("update", bytesRead);
        pro.setProgress((int) ((double) bytesRead / contentLength * 100));
        temp++;
        if (temp <= 1) {
          Log.e("MainActivity", "update" + bytesRead + "");
        }
      }
    });
    RetrofitHelper.download(0, -1, "QQ_718.apk", new File("mnt/sdcard/", "aaaaaaaaa.apk"), subscriber).subscribe(new Subscriber() {
      @Override
      public void onCompleted() {

      }

      @Override
      public void onError(Throwable e) {

      }

      @Override
      public void onNext(Object o) {

      }
    });

  }

 注:最后貼一個apk安裝的方法

  // 安裝APK
  public void installAPK(String filePath) {
    Intent intent = new Intent();
    intent.setAction("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 廣播里面操作需要加上這句,存在于一個獨立的棧里
    intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
    mainActivity.startActivity(intent);
  }

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 淺析java中next與nextLine用法對比

    淺析java中next與nextLine用法對比

    這篇文章主要介紹了java中next與nextLine用法區(qū)別以及實例分析了他們的區(qū)別,需要的朋友可以參考下
    2017-04-04
  • SpringBoot bean查詢加載順序流程詳解

    SpringBoot bean查詢加載順序流程詳解

    當你在項目啟動時需要提前做一個業(yè)務(wù)的初始化工作時,或者你正在開發(fā)某個中間件需要完成自動裝配時。你會聲明自己的Configuration類,但是可能你面對的是好幾個有互相依賴的Bean
    2023-03-03
  • Java數(shù)字圖像處理之圖像灰度處理

    Java數(shù)字圖像處理之圖像灰度處理

    這篇文章主要為大家詳細介紹了Java數(shù)字圖像處理之圖像灰度處理,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • JAVA設(shè)計模式---單例模式你知道嗎

    JAVA設(shè)計模式---單例模式你知道嗎

    這篇文章主要給大家介紹了關(guān)于Java單例模式,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Java具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2021-09-09
  • Java 找不到或無法加載主類的修復方法

    Java 找不到或無法加載主類的修復方法

    這篇文章主要介紹了Java 找不到或無法加載主類的修復方法,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2021-02-02
  • java中ArrayList和LinkedList的區(qū)別詳解

    java中ArrayList和LinkedList的區(qū)別詳解

    這篇文章主要介紹了java中ArrayList和LinkedList的區(qū)別詳解,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2021-01-01
  • java管道piped輸入流與輸出流應用場景案例分析

    java管道piped輸入流與輸出流應用場景案例分析

    這篇文章主要介紹了java管道流PipedInputStream與PipedOutputStream(輸入流與輸出流)的應用場景案例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2022-02-02
  • java多線程Future和Callable類示例分享

    java多線程Future和Callable類示例分享

    JAVA多線程實現(xiàn)方式主要有三種:繼承Thread類、實現(xiàn)Runnable接口、使用ExecutorService、Callable、Future實現(xiàn)有返回結(jié)果的多線程。其中前兩種方式線程執(zhí)行完后都沒有返回值,只有最后一種是帶返回值的。今天我們就來研究下Future和Callable的實現(xiàn)方法
    2016-01-01
  • Intellij IDEA 2017.3使用Lombok及常用注解介紹

    Intellij IDEA 2017.3使用Lombok及常用注解介紹

    這篇文章主要介紹了Intellij IDEA 2017.3使用Lombok及常用注解介紹,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-09-09
  • 基于重定向RedirectAttributes的用法解析

    基于重定向RedirectAttributes的用法解析

    這篇文章主要介紹了基于重定向RedirectAttributes的用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12

最新評論