我有一个pdf查看器应用程序,在这里我必须下载大的pdf文件(例如136mb),我正在使用Retrofit2-beta2进行此过程。问题是我总是内存不足。我怎样才能告诉翻新我将下载一个大文件,请仅将byteStream给我?
我的界面是:
@GET("url")
Call<ResponseBody> getData(params);
我有一个ProgressResponseBody类,它正在扩展ResponseBody,并且在这里设置一个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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句