使用 Retrofit 2 下载文件时内存不足

Out of Memory using Retrofit 2 for downloading a file

我有一个 pdf 查看器应用程序,我必须在其中下载大的 pdf 文件(例如 136mb)我正在使用 retrofit2-beta2 进行此过程。问题是我总是 运行 内存不足。我怎么能告诉改造我将下载一个大文件请把字节流给我?

我的界面是:

@GET("url")
Call<ResponseBody> getData(params);

我有一个正在扩展 ResponseBody 的 ProgressResponseBody class 我在这里设置了一个 progressListener,以便能够刷新我的进度条,

并且在 onResponse 函数中我得到了像

这样的 InputStream
InputStream input = response.body().byteStream();
FileOutputStream out = new FileOutputStream(file);
int bufferSize=1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while (len = input.read(buffer) != -1) {
    out.write(buffer,0,len);
} 
if(out!=null)
    out.close();

更新

我已将 @Stream 添加到界面,但现在我在 ProgressResponseBody.java 中得到 NetworkOnMainThreadException 错误抛出在 super.read(sink,byteCount);排。我怎么能把它放到一个单独的线程中?

@Override
    public BufferedSource source() throws IOException {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
                return bytesRead;
            }
        };
    }

@Streaming 注释添加到您的调用以获取原始 ResponseBody

@Streaming
@GET("url")
Call<ResponseBody> getData(params);