我已经看过了
Is it possible to check progress of URLconnection.getInputStream()? https://stackoverflow.com/a/20120451/5437621
我正在使用以下代码从互联网下载文件:
try {
InputStream is = new URL(pdfUrl).openStream();
byte[] pdfData = readBytes(is);
return pdfData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
public byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
是否有任何方法可以获取正在下载的文件的进度?
我看到的答案是使用while
循环,但在这种情况下我不明白如何使用它。
修改
我在AsyncTask中使用它:
protected byte[] doInBackground(String... url) {
pdfUrl = url[0];
try {
InputStream is = new URL(pdfUrl).openStream();
DownloadBytes downloadData = readBytes(is);
byte[] pdfData = downloadData.getBytes();
progress = downloadData.getProgress();
return pdfData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
如何在此方法中调整publishProgress()
?