use of com.lzy.okgo.callback.FileCallback in project okhttp-OkGo by jeasonlzy.
the class RxFileDownloadActivity method fileDownload2.
@OnClick(R.id.fileDownload2)
public void fileDownload2(View view) {
Observable.create(new ObservableOnSubscribe<Progress>() {
@Override
public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
String etString = etUrl.getText().toString();
String url = TextUtils.isEmpty(etString) ? Urls.URL_DOWNLOAD : etString;
//
OkGo.<File>get(url).headers("aaa", //
"111").params("bbb", //
"222").execute(new FileCallback() {
@Override
public void onSuccess(Response<File> response) {
e.onComplete();
}
@Override
public void onError(Response<File> response) {
e.onError(response.getException());
}
@Override
public void downloadProgress(Progress progress) {
e.onNext(progress);
}
});
}
}).doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(@NonNull Disposable disposable) throws Exception {
btnFileDownload2.setText("正在下载中...");
}
}).observeOn(//
AndroidSchedulers.mainThread()).subscribe(new Observer<Progress>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
addDisposable(d);
}
@Override
public void onNext(@NonNull Progress progress) {
String downloadLength = Formatter.formatFileSize(getApplicationContext(), progress.currentSize);
String totalLength = Formatter.formatFileSize(getApplicationContext(), progress.totalSize);
tvDownloadSize.setText(downloadLength + "/" + totalLength);
String speed = Formatter.formatFileSize(getApplicationContext(), progress.speed);
tvNetSpeed.setText(String.format("%s/s", speed));
tvProgress.setText(numberFormat.format(progress.fraction));
pbProgress.setMax(10000);
pbProgress.setProgress((int) (progress.fraction * 10000));
}
@Override
public void onError(@NonNull Throwable e) {
e.printStackTrace();
btnFileDownload2.setText("下载出错");
showToast(e.getMessage());
}
@Override
public void onComplete() {
btnFileDownload2.setText("下载完成");
}
});
}
Aggregations