I have an AsyncTask that downloads several images that I pass through an ArrayList with the download links and I use a progress bar and it is not working perfectly.
The progress bar restarts every link that downloads the image, I think I have to add the size of each image of the links and then start to make the progress bar to run, to test I have an ArrayList with 9 links progress bar restarts 9 times.
What would be the best way to implement a progress bar with several download?
class DownloadTask extends AsyncTask<ArrayList<String>, Integer, String> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.setTitle("Download em progresso...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
@Override
protected String doInBackground(ArrayList<String>... params) {
ArrayList<String> path = params[0];
int count = 0;
for (String urlImage : path) {
int file_length = 0;
try {
URL url = new URL(urlImage);
URLConnection urlconnection = url.openConnection();
urlconnection.connect(); // ok
file_length = urlconnection.getContentLength();
String fileName = Uri.parse(String.valueOf(url)).getLastPathSegment();
File imput_file = new File(new_folder, fileName);
InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
byte[] data = new byte[1024];
int total = 0;
OutputStream outputStream = new FileOutputStream(imput_file);
while ((count = inputStream.read(data)) != -1) {
total += count;
outputStream.write(data, 0, count);
int progress = (int) total * 100 / file_length;
publishProgress(progress);
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "Download finalizado!";
}
@Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(String result) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
Thanks.