最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Retrofit+Rxjava實現(xiàn)帶進(jìn)度顯示的下載文件

 更新時間:2018年05月09日 17:21:22   作者:JokAr-  
這篇文章主要為大家詳細(xì)介紹了基于Retrofit+Rxjava實現(xiàn)帶進(jìn)度顯示的下載文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了Retrofit Rxjava實現(xiàn)下載文件的具體代碼,供大家參考,具體內(nèi)容如下

本文采用 :retrofit + rxjava

1.引入:

//rxJava
 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.增加下載進(jìn)度監(jiān)聽:

public interface DownloadProgressListener {
 void update(long bytesRead, long contentLength, boolean done);
}
public class DownloadProgressResponseBody extends ResponseBody {

 private ResponseBody responseBody;
 private DownloadProgressListener progressListener;
 private BufferedSource bufferedSource;

 public DownloadProgressResponseBody(ResponseBody responseBody,
          DownloadProgressListener progressListener) {
  this.responseBody = responseBody;
  this.progressListener = progressListener;
 }

 @Override
 public MediaType contentType() {
  return responseBody.contentType();
 }

 @Override
 public long contentLength() {
  return responseBody.contentLength();
 }

 @Override
 public BufferedSource source() {
  if (bufferedSource == null) {
   bufferedSource = Okio.buffer(source(responseBody.source()));
  }
  return bufferedSource;
 }

 private Source source(Source source) {
  return new ForwardingSource(source) {
   long totalBytesRead = 0L;

   @Override
   public long read(Buffer sink, long byteCount) throws IOException {
    long bytesRead = super.read(sink, byteCount);
    // read() returns the number of bytes read, or -1 if this source is exhausted.
    totalBytesRead += bytesRead != -1 ? bytesRead : 0;

    if (null != progressListener) {
     progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
    }
    return bytesRead;
   }
  };

 }
}

public class DownloadProgressInterceptor implements Interceptor {

 private DownloadProgressListener listener;

 public DownloadProgressInterceptor(DownloadProgressListener listener) {
  this.listener = listener;
 }

 @Override
 public Response intercept(Chain chain) throws IOException {
  Response originalResponse = chain.proceed(chain.request());

  return originalResponse.newBuilder()
    .body(new DownloadProgressResponseBody(originalResponse.body(), listener))
    .build();
 }
}

3.創(chuàng)建下載進(jìn)度的元素類:

public class Download implements Parcelable {

 private int progress;
 private long currentFileSize;
 private long totalFileSize;

 public int getProgress() {
  return progress;
 }

 public void setProgress(int progress) {
  this.progress = progress;
 }

 public long getCurrentFileSize() {
  return currentFileSize;
 }

 public void setCurrentFileSize(long currentFileSize) {
  this.currentFileSize = currentFileSize;
 }

 public long getTotalFileSize() {
  return totalFileSize;
 }

 public void setTotalFileSize(long totalFileSize) {
  this.totalFileSize = totalFileSize;
 }

 @Override
 public int describeContents() {
  return 0;
 }

 @Override
 public void writeToParcel(Parcel dest, int flags) {
  dest.writeInt(this.progress);
  dest.writeLong(this.currentFileSize);
  dest.writeLong(this.totalFileSize);
 }

 public Download() {
 }

 protected Download(Parcel in) {
  this.progress = in.readInt();
  this.currentFileSize = in.readLong();
  this.totalFileSize = in.readLong();
 }

 public static final Parcelable.Creator<Download> CREATOR = new Parcelable.Creator<Download>() {
  @Override
  public Download createFromParcel(Parcel source) {
   return new Download(source);
  }

  @Override
  public Download[] newArray(int size) {
   return new Download[size];
  }
 };
}

4.下載文件網(wǎng)絡(luò)類:

public interface DownloadService {

 @Streaming
 @GET
 Observable<ResponseBody> download(@Url String url);
}

注:這里@Url是傳入完整的的下載URL;不用截取

public class DownloadAPI {
 private static final String TAG = "DownloadAPI";
 private static final int DEFAULT_TIMEOUT = 15;
 public Retrofit retrofit;


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

 public void downloadAPK(@NonNull String url, final File file, Subscriber subscriber) {
  Log.d(TAG, "downloadAPK: " + url);

  retrofit.create(DownloadService.class)
    .download(url)
    .subscribeOn(Schedulers.io())
    .unsubscribeOn(Schedulers.io())
    .map(new Func1<ResponseBody, InputStream>() {
     @Override
     public InputStream call(ResponseBody responseBody) {
      return responseBody.byteStream();
     }
    })
    .observeOn(Schedulers.computation())
    .doOnNext(new Action1<InputStream>() {
     @Override
     public void call(InputStream inputStream) {
      try {
       FileUtils.writeFile(inputStream, file);
      } catch (IOException e) {
       e.printStackTrace();
       throw new CustomizeException(e.getMessage(), e);
      }
     }
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(subscriber);
 }


}

然后就是調(diào)用了:

該網(wǎng)絡(luò)是在service里完成的

public class DownloadService extends IntentService {
 private static final String TAG = "DownloadService";

 private NotificationCompat.Builder notificationBuilder;
 private NotificationManager notificationManager;


 private String apkUrl = "http://download.fir.im/v2/app/install/595c5959959d6901ca0004ac?download_token=1a9dfa8f248b6e45ea46bc5ed96a0a9e&source=update";

 public DownloadService() {
  super("DownloadService");
 }

 @Override
 protected void onHandleIntent(Intent intent) {
  notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  notificationBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.mipmap.ic_download)
    .setContentTitle("Download")
    .setContentText("Downloading File")
    .setAutoCancel(true);

  notificationManager.notify(0, notificationBuilder.build());

  download();
 }

 private void download() {
  DownloadProgressListener listener = new DownloadProgressListener() {
   @Override
   public void update(long bytesRead, long contentLength, boolean done) {
    Download download = new Download();
    download.setTotalFileSize(contentLength);
    download.setCurrentFileSize(bytesRead);
    int progress = (int) ((bytesRead * 100) / contentLength);
    download.setProgress(progress);

    sendNotification(download);
   }
  };
  File outputFile = new File(Environment.getExternalStoragePublicDirectory
    (Environment.DIRECTORY_DOWNLOADS), "file.apk");
  String baseUrl = StringUtils.getHostName(apkUrl);

  new DownloadAPI(baseUrl, listener).downloadAPK(apkUrl, outputFile, new Subscriber() {
   @Override
   public void onCompleted() {
    downloadCompleted();
   }

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

   @Override
   public void onNext(Object o) {

   }
  });
 }

 private void downloadCompleted() {
  Download download = new Download();
  download.setProgress(100);
  sendIntent(download);

  notificationManager.cancel(0);
  notificationBuilder.setProgress(0, 0, false);
  notificationBuilder.setContentText("File Downloaded");
  notificationManager.notify(0, notificationBuilder.build());
 }

 private void sendNotification(Download download) {

  sendIntent(download);
  notificationBuilder.setProgress(100, download.getProgress(), false);
  notificationBuilder.setContentText(
    StringUtils.getDataSize(download.getCurrentFileSize()) + "/" +
      StringUtils.getDataSize(download.getTotalFileSize()));
  notificationManager.notify(0, notificationBuilder.build());
 }

 private void sendIntent(Download download) {

  Intent intent = new Intent(MainActivity.MESSAGE_PROGRESS);
  intent.putExtra("download", download);
  LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
 }

 @Override
 public void onTaskRemoved(Intent rootIntent) {
  notificationManager.cancel(0);
 }
}

MainActivity代碼:

public class MainActivity extends AppCompatActivity {

 public static final String MESSAGE_PROGRESS = "message_progress";

 private AppCompatButton btn_download;
 private ProgressBar progress;
 private TextView progress_text;


 private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {

   if (intent.getAction().equals(MESSAGE_PROGRESS)) {

    Download download = intent.getParcelableExtra("download");
    progress.setProgress(download.getProgress());
    if (download.getProgress() == 100) {

     progress_text.setText("File Download Complete");

    } else {

     progress_text.setText(StringUtils.getDataSize(download.getCurrentFileSize())
       +"/"+
       StringUtils.getDataSize(download.getTotalFileSize()));

    }
   }
  }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  btn_download = (AppCompatButton) findViewById(R.id.btn_download);
  progress = (ProgressBar) findViewById(R.id.progress);
  progress_text = (TextView) findViewById(R.id.progress_text);

  registerReceiver();

  btn_download.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    Intent intent = new Intent(MainActivity.this, DownloadService.class);
    startService(intent);
   }
  });
 }

 private void registerReceiver() {

  LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
  IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction(MESSAGE_PROGRESS);
  bManager.registerReceiver(broadcastReceiver, intentFilter);

 }
}

本文源碼:Retrofit Rxjava實現(xiàn)下載文件

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

相關(guān)文章

  • Java?RabbitMQ的持久化和發(fā)布確認(rèn)詳解

    Java?RabbitMQ的持久化和發(fā)布確認(rèn)詳解

    這篇文章主要為大家詳細(xì)介紹了RabbitMQ的持久化和發(fā)布確認(rèn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • java8中的默認(rèn)垃圾回收器(GC)

    java8中的默認(rèn)垃圾回收器(GC)

    這篇文章主要介紹了java8中的默認(rèn)垃圾回收器(GC),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • PageHelper在springboot中的使用方式

    PageHelper在springboot中的使用方式

    這篇文章主要介紹了PageHelper在springboot中的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Java11中的新增字符串APIs使用實例探究

    Java11中的新增字符串APIs使用實例探究

    這篇文章主要為大家介紹了Java11中的新增字符串APIs使用實例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • Java?NIO實現(xiàn)聊天系統(tǒng)

    Java?NIO實現(xiàn)聊天系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Java?NIO實現(xiàn)聊天系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Java導(dǎo)出Word文檔的四種方法

    Java導(dǎo)出Word文檔的四種方法

    在日常的開發(fā)工作中,我們時常會遇到導(dǎo)出Word文檔報表的需求,比如公司的財務(wù)報表、醫(yī)院的患者統(tǒng)計報表、電商平臺的銷售報表等等,所以本文給大家介紹了Java導(dǎo)出Word文檔的四種方法,并通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下
    2025-03-03
  • java調(diào)用ffmpeg實現(xiàn)視頻轉(zhuǎn)換的方法

    java調(diào)用ffmpeg實現(xiàn)視頻轉(zhuǎn)換的方法

    這篇文章主要介紹了java調(diào)用ffmpeg實現(xiàn)視頻轉(zhuǎn)換的方法,較為詳細(xì)分析了java視頻格式轉(zhuǎn)換所需要的步驟及具體實現(xiàn)技巧,需要的朋友可以參考下
    2015-06-06
  • Java泛型常見面試題(面試必問)

    Java泛型常見面試題(面試必問)

    泛型在java中有很重要的地位,在面向?qū)ο缶幊碳案鞣N設(shè)計模式中有非常廣泛的應(yīng)用。java泛型知識點也是Java開發(fā)崗位必問的一個話題,今天小編就給大家普及下Java泛型常見面試題,感興趣的朋友一起看看吧
    2021-06-06
  • idea2020.1.3 手把手教你創(chuàng)建web項目的方法步驟

    idea2020.1.3 手把手教你創(chuàng)建web項目的方法步驟

    這篇文章主要介紹了idea 2020.1.3 手把手教你創(chuàng)建web項目的方法步驟,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • spring實例化javabean的三種方式分享

    spring實例化javabean的三種方式分享

    這篇文章介紹了spring實例化javabean的三種方式,有需要的朋友可以參考一下
    2013-10-10

最新評論

沙河市| 德钦县| 巴楚县| 伊通| 墨脱县| 广安市| 德兴市| 海口市| 广汉市| 长寿区| 漳州市| 伊宁市| 金阳县| 土默特右旗| 兖州市| 丽江市| 汪清县| 长岭县| 常州市| 青川县| 江都市| 合肥市| 茶陵县| 建阳市| 浦北县| 土默特右旗| 商南县| 新津县| 屯门区| 余江县| 鄂尔多斯市| 隆子县| 平陆县| 延安市| 光泽县| 蕉岭县| 勃利县| 左权县| 上蔡县| 旌德县| 南木林县|