在Android中使用RxJava,OkHttp和Okio的下载进度 [英] Download progress with RxJava, OkHttp and Okio in Android
本文介绍了在Android中使用RxJava,OkHttp和Okio的下载进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我们的应用程序中,我使用此代码下载了一个图像文件.我需要在UI上显示下载进度(已下载字节数百分比).如何获得此代码中的下载进度?我在寻找解决方案,但仍然无法自行解决.
In our app I download an image file with this code. I need to show download progress(downloaded bytes in percentage) on UI. How I can get download progress in this code? I searched for solution, but still can't manage to do it on my own.
Observable<String> downloadObservable = Observable.create(
sub -> {
Request request = new Request.Builder()
.url(media.getMediaUrl())
.build();
Response response = null;
try {
response = http_client.newCall(request).execute();
if (response.isSuccessful()) {
Log.d(TAG, "response.isSuccessful()");
String mimeType = MimeTypeMap.getFileExtensionFromUrl(media.getMediaUrl());
File file = new File(helper.getTmpFolder() + "/" + helper.generateUniqueName() + "test." + mimeType);
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(response.body().source());
sink.close();
sub.onNext(response.toString());
sub.onCompleted();
} else {
sub.onError(new IOException());
}
} catch (IOException e) {
e.printStackTrace();
}
}
);
Subscriber<String> mySubscriber = new Subscriber<String>() {
@Override
public void onNext(String responseString) {
Log.d(TAG, "works: " + responseString);
}
};
downloadObservable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mySubscriber);
推荐答案
这就是我要显示进度的方法.
This is what I would do to display progress.
Observable<String> downloadObservable = Observable.create(
sub -> {
InputStream input = null;
OutputStream output = null;
try {
Response response = http_client.newCall(request).execute();
if (response.isSuccessful()) {
input = response.body().byteStream();
long tlength= response.body().contentLength();
output = new FileOutputStream("/pathtofile");
byte data[] = new byte[1024];
sub.onNext("0%");
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
sub.onNext(String.valueOf(total*100/tlength) + "%");
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
} catch(IOException e){
sub.onError(e);
} finally {
if (input != null){
try {
input.close();
}catch(IOException ioe){}
}
if (out != null){
try{
output.close();
}catch (IOException e){}
}
}
sub.onCompleted();
}
);
并使用具有完整抽象方法的订阅服务器.
And use the Subscriber that has the complete abstract methods.
Subscriber<String> mySubscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
// hide progress bar
}
@Override
public void onError(Throwable e) {
// hide progress bar
}
@Override
public void onNext(String percentProgress) {
// show percentage progress
}
};
这篇关于在Android中使用RxJava,OkHttp和Okio的下载进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文