I am facing an issue I am using retrofit2 for file downloading and I want to show file downloading progress from 1% to 100%. The progress bar is only updated to 100% when file downloaded completely but I want the progress of file shown while the file is downloading here is the code I have tried so far. Looking forward to your solutions.
private void downloadPdfFile() {
progressBar.setVisibility(View.VISIBLE);
progressBar.setMax(100);
progressBar.setProgress(0);
Call<ResponseBody> response = mPdfDownloadService.downloadPdfBook(fileName);
response.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
saveToDisk(response.body());
}
});
progressBar.setVisibility(View.GONE);
Toast.makeText(BooksByClassActivity.this, "File downloaded Successfully ", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(BooksByClassActivity.this, "Unable to connect", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
//Method to download Pdf file and to save in phone storage
private boolean saveToDisk(ResponseBody body) {
try {
// todo change the file location/name according to your needs
File pdfFile = new File(getFilesDir() + File.separator + fileName);
InputStream inputStream = null;
OutputStream outputStream = null;
long progress = 0;
int count;
byte[] data = new byte[4096];
try {
long fileSize = body.contentLength();
inputStream = body.byteStream();
outputStream = new FileOutputStream(pdfFile);
while ((count = inputStream.read(data)) != -1) {
progress += count;
long finalProgress = progress;
Log.d("Progress", "" + (int) ((finalProgress * 100) / fileSize));
progressBar.setProgress((int) ((finalProgress * 100) / fileSize));
outputStream.write(data, 0, count);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}