I have a progress bar managed by a AsyncTask which downloads some files from the internet.
private class DownloadImgs extends AsyncTask<Void, String, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
@Override
protected Void doInBackground(Void ...params) {
for(GetCountry gc : listCountry){
getdownloadedFiles(gc.getUrl());}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(Void result) {
dismissDialog(progress_bar_type);
}
The method which allows me to download the files:
public void getdownloadedFiles(String url)
{
int count;
try {
URL urlImg = new URL(url);
URLConnection connection = urlImg.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream input = new BufferedInputStream(urlImg.openStream(), 8192);
OutputStream output = new FileOutputStream(folder+"/"+name);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.getMessage();
}
}
This code works well, but the problem is that each file downloaded has it’s own progress bar
I want only one progress bar for all the downloaded files.
How can I achieve this?
Thank you very much
In your
doInBackground()method, simply loop over the list of files you need to download inside of the single execution of yourAsyncTask. You should probably also leverage the varargs nature ofexecute()to pass the list of URLs you need to download. In other words, something close to this:The modify the task as such:
EDIT:
One method you could use to display all the file downloads as a single contiguous progress indicator is simply to update the progress by file count alone rather than file content. In other words, if you have 5 files just
publishProgress()with values of 20 (1 * 100 / 5), 40 (2 * 100 / 5), 60 (3 * 100 / 5), 80 (4 * 100 / 5), and 100 (5 * 100 / 5) at the end of each file download.If you need something more granular without pre-fetching the content length of every file, make each chunk increment with percentage. Note that you can also set the maximum level of the progress bar with
setMax()to something other than 100 to make the math easier to work with. In the same 5 files example, you can set the progress bar maximum to 500, and for each download you would still add 100 to the total in the same fashion as you are now, but the total does not reset at the beginning of each download.