在Android中使用RxJava、OkHttp和Okio实现下载进度

15

在我们的应用程序中,我使用这段代码下载图像文件。我需要在用户界面上显示下载进度(已下载字节数的百分比)。我该如何在这段代码中获取下载进度?我搜索了解决方法,但仍然无法自行完成。

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

找到了一个与我的问题相关的好例子 http://danosipov.com/?p=678 - Rafael
2个回答

24

这是我用来显示进度的方法。

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

我的意思是我需要以百分比显示下载进度。 - Rafael
2
我更新了我的回答,但我不了解Okio,所以无法谈论它。 - inmyth
2
@inmyth 你怎么访问这个文件? - nani
1
同意@nani的观点,这个Observable的目的是返回文件,进度不是主要部分。我认为这不应该被批准作为答案。 - Dominik Mičuta
1
为什么人们不断推荐使用Observable.create?那可不是你应该做的方式。 - Noah Andrews
显示剩余4条评论

0

被接受的答案只显示了保存下载文件的进度,而没有实际下载进度。

使用 Kotlin 创建了具有进度解决方案的 Rx 下载文件,希望能有所帮助:

private const val FULL_PROGRESS = 100L

class DownloadWithProgress {

    fun start(url: String, directory: File, fileName: String) =
        Observable.create<Download> { emitter ->
            try {
                val request = Request.Builder()
                    .url(url)
                    .build()

                OkHttpClient.Builder()
                    .addNetworkInterceptor { chain: Interceptor.Chain ->
                        val originalResponse = chain.proceed(chain.request())
                        originalResponse.newBuilder()
                            .body(originalResponse.body()?.let { responseBody ->
                                ProgressResponseBody(responseBody) { emitter.onNext(Download(it)) }
                            })
                            .build()
                    }
                    .build()
                    .newCall(request).execute().use { response ->
                        if (!response.isSuccessful) throw IOException("Unexpected code $response")
                        val bufferedSource = response.body()?.source() ?: throw NullPointerException("Response is null")

                        try {
                            val packageFile = File(directory, fileName).apply {
                                sink().buffer().run {
                                    writeAll(bufferedSource)
                                    close()
                                }
                            }

                            emitter.onNext(Download(FULL_PROGRESS, packageFile))
                        } catch (ioException: Exception) {
                            throw AppUpdateException("Io exception: " + ioException.localizedMessage)
                        }

                        emitter.onComplete()
                    }
            } catch (exception: Exception) {
                emitter.onError(exception)
            }
        }

    private class ProgressResponseBody(
        private val responseBody: ResponseBody,
        private val onProgress: (progress: Long) -> Unit
    ) : ResponseBody() {

        private var bufferedSource: BufferedSource? = null

        override fun contentType() = responseBody.contentType()

        override fun contentLength() = responseBody.contentLength()

        override fun source() = bufferedSource ?: source(responseBody.source()).buffer().also { bufferedSource = it }

        private fun source(source: Source): Source {
            return object : ForwardingSource(source) {
                var totalBytesRead = 0L

                override fun read(sink: Buffer, byteCount: Long): Long {
                    return super.read(sink, byteCount).apply {
                        val bytesRead = this
                        totalBytesRead += if (bytesRead != -1L) bytesRead else 0

                        if (bytesRead != -1L) {
                            val progress = FULL_PROGRESS * totalBytesRead / responseBody.contentLength()
                            onProgress(progress)
                        }
                    }
                }
            }
        }
    }
}

data class Download(
    val progress: Long,
    val file: File? = null
) {
    val isDownloaded = progress == FULL_PROGRESS && file != null
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接