答案 0 :(得分:24)
private class AsyncDownloader extends AsyncTask<Void, Long, Boolean> {
private final String URL = "file_url";
@Override
protected Boolean doInBackground(Void... params) {
OkHttpClient httpClient = new OkHttpClient();
Call call = httpClient.newCall(new Request.Builder().url(URL).get().build());
try {
Response response = call.execute();
if (response.code() == 200) {
InputStream inputStream = null;
try {
inputStream = response.body().byteStream();
byte[] buff = new byte[1024 * 4];
long downloaded = 0;
long target = response.body().contentLength();
publishProgress(0L, target);
while (true) {
int readed = inputStream.read(buff);
if(readed == -1){
break;
}
//write buff
downloaded += readed;
publishProgress(downloaded, target);
if (isCancelled()) {
return false;
}
}
return downloaded == target;
} catch (IOException ignore) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onProgressUpdate(Long... values) {
progressBar.setMax(values[1].intValue());
progressBar.setProgress(values[0].intValue());
textViewProgress.setText(String.format("%d / %d", values[0], values[1]));
}
@Override
protected void onPostExecute(Boolean result) {
textViewStatus.setText(result ? "Downloaded" : "Failed");
}
}
答案 1 :(得分:2)
您可以使用okHttp receipe:Progress.java
答案 2 :(得分:0)
每次在while循环中,您都会发布进度。所以它就像被阻止一样