android - 在 Android 中使用 RxJava、OkHttp 和 Okio 下载进度

标签 android rx-java okhttp okio

在我们的应用程序中,我使用此代码下载图像文件。我需要在 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, 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();
   }
);

并使用具有完整抽象方法的Subscriber。

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 - 在 Android 中使用 RxJava、OkHttp 和 Okio 下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958881/

相关文章:

OkHttp API速率限制

Java声明对象但在 'if'内分配它是行不通的

android - Android:如何在Kotlin中将string.xml中的R.string值设置为全局常量?

android - 如何知道android中应用程序的显示大小?

android - 为什么我的 RxJava Observable 没有完成?

java - 在 rxAndroid 中返回对象的 ArrayList

android - Android 中的 HttpURLConnection 工作正常,但 OkHttp 在 Kitkat 上给出 "Network is unreachable"

android - FrameLayout 不适合它的空间

android - 如何创建像 Hangouts 应用程序一样的 MenuDrawer?

java - 如何从 void 方法返回 Completable