亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 開發 > Java > 正文

基于Retrofit+Rxjava實現帶進度顯示的下載文件

2024-07-14 08:40:44
字體:
來源:轉載
供稿:網友

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

本文采用 :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.增加下載進度監聽:

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.創建下載進度的元素類:

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.下載文件網絡類:

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

然后就是調用了:

該網絡是在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實現下載文件

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
亚洲精品电影网在线观看| 精品福利樱桃av导航| 在线观看欧美成人| 日韩欧美精品在线观看| 亚洲国产精品人久久电影| 国产视频久久网| 亚洲精品资源美女情侣酒店| 国产精品精品视频| 国产在线不卡精品| 日韩av电影在线免费播放| 国产不卡在线观看| 91精品久久久久久久| 国产成人免费91av在线| 日本中文字幕不卡免费| 欧美壮男野外gaytube| 欧美成人免费全部| 日日摸夜夜添一区| 亚洲成人精品视频| 久久免费观看视频| 国产福利成人在线| 97超级碰在线看视频免费在线看| 精品网站999www| 欧美精品videos性欧美| 日韩免费黄色av| 久久精品电影网站| 久久久久久久一区二区| 成人福利视频网| 538国产精品一区二区免费视频| 精品久久久久久亚洲精品| 久久伊人精品视频| 久久精彩免费视频| 成人免费xxxxx在线观看| 日韩在线视频网| 欧美与欧洲交xxxx免费观看| 欧美电影免费观看电视剧大全| 色综合久久悠悠| 欧美大尺度电影在线观看| 久久久久久网址| 78m国产成人精品视频| 日韩大片在线观看视频| 91精品成人久久| 亚洲老头同性xxxxx| 欧美激情欧美激情在线五月| 色老头一区二区三区在线观看| 91人人爽人人爽人人精88v| 欧美日韩中国免费专区在线看| 亚洲精品一区av在线播放| 日韩电影中文字幕av| 色播久久人人爽人人爽人人片视av| 福利二区91精品bt7086| 久久精品91久久久久久再现| 日韩av手机在线看| 亚洲va男人天堂| 国产精品h片在线播放| 久久精品中文字幕电影| 亚洲成色777777女色窝| 国产精品久久久一区| 欧美另类精品xxxx孕妇| 国产69精品久久久久99| 久久偷看各类女兵18女厕嘘嘘| 国产精品福利在线观看| x99av成人免费| 丝袜美腿精品国产二区| 成人精品福利视频| 欧美精品成人在线| 亚洲高清一二三区| 激情久久av一区av二区av三区| 亚洲91精品在线| 国产69久久精品成人| 亚洲最大福利网站| 欧美亚洲成人精品| 欧美激情亚洲另类| 色老头一区二区三区在线观看| 91精品久久久久久久久久| 欧美黄色片视频| 国产精品999| 深夜精品寂寞黄网站在线观看| 狠狠躁天天躁日日躁欧美| 欧美性高潮床叫视频| 亚洲国产成人在线播放| 一区二区三区视频免费| 一色桃子一区二区| 不卡av在线网站| 亚洲一区二区三区视频播放| 国产成人精品av在线| 国产精品一区电影| 欧美激情videos| 国产成人精品久久二区二区| 久久久久久国产三级电影| 亚洲欧洲黄色网| 午夜剧场成人观在线视频免费观看| 92裸体在线视频网站| 欧美成人四级hd版| 色婷婷av一区二区三区久久| 精品福利一区二区| 国产美女久久精品香蕉69| 麻豆精品精华液| 亚洲欧美制服综合另类| 神马国产精品影院av| 中文字幕av一区| 欧美床上激情在线观看| 另类色图亚洲色图| 国产精品免费视频xxxx| 这里只有精品在线观看| 国产日产亚洲精品| 91精品国产自产在线观看永久| 欧美特级www| 欧美日韩午夜剧场| 久久久久久久久久久成人| 亚洲第一区第一页| 欧美激情亚洲国产| 日本欧美国产在线| 久久6精品影院| 成人av在线网址| 亚洲性av网站| 日韩电影中文字幕一区| 精品二区三区线观看| 久久综合色88| 欧美性猛交xxx| 欧美性感美女h网站在线观看免费| 韩国一区二区电影| 日韩av影片在线观看| 欧美午夜www高清视频| 欧洲午夜精品久久久| 国产91久久婷婷一区二区| 国产精品揄拍一区二区| 青草青草久热精品视频在线网站| 久久久极品av| 国产精品视频导航| 中文在线资源观看视频网站免费不卡| 欧美日韩国产色视频| 亚洲免费成人av电影| 一夜七次郎国产精品亚洲| 69久久夜色精品国产69| 国产精品一区=区| 91成人福利在线| 97久久精品国产| 精品国产乱码久久久久酒店| 日韩欧美一区视频| 日本精品一区二区三区在线| 在线成人激情视频| 久久不射电影网| 欧美精品videosex牲欧美| 欧美亚洲日本网站| 成人黄色激情网| 亚洲天堂av电影| 亚洲精品免费在线视频| 精品久久久久久国产| 国产香蕉97碰碰久久人人| 亚洲国产精品成人一区二区| 久久69精品久久久久久国产越南| 中文字幕九色91在线| 国产精品国模在线| 国产欧美精品一区二区| 综合激情国产一区| 欧美日韩免费区域视频在线观看| 97国产精品久久| 久热精品视频在线观看一区| 亚洲美女av网站| 亚洲电影免费观看高清| 欧美日韩激情小视频| 欧美亚洲另类制服自拍| 97av在线视频| 久久久噜噜噜久久久|