在我们的应用程序中,我使用此代码下载一个图像文件我需要在UI上显示下载进度(以百分比形式下载的字节数).如何在这段代码中获得下载进度?我搜索解决方案,但仍然无法自行设法完成.
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);
解决方法
这是我会做的以显示进度.
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,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(); } );
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 } };