Reputation: 437
I have a program with one button click, when clicked, 4 Downloads should executed Simultaneously. I use ASyncTask
class for this purpose with for
iterator:
for(int i=0;i<downloadCounts;i++){
new DownloadTask().execute(url[i]);
}
but in running, only one download executed and all 4 progressbars show that single download. I want to download 4 downloads in same time. how can I do?
for more details, my download manager, get a link and divide it to 4 chunks according to file size. then with above for
iterator , command it to run 4 parts download with this class:
private class DownloadChunks extends AsyncTask<Long,String,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
setStatusText(-1);
}
@Override
protected String doInBackground(Long... params) {
long s1 = params[0];
long s2 = params[1];
int count;
try{
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Range", "bytes=" + s1 + "-" + s2);
connection.connect();
len2 = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),8192);
File file = new File(Environment.getExternalStorageDirectory()+"/nuhexxxx");
if(!file.exists())file.mkdirs();
OutputStream output = new FileOutputStream(file+"/nuhe1.mp3");
byte[] data = new byte[1024];
long total = 0;
while ((count= input.read(data))!=-1){
total += count;
publishProgress(""+(int)((total*100)/len2));
output.write(data,0,count);
}
output.flush();
output.close();
input.close();
counter++;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
setStatusText(Integer.parseInt(values[0]));
}
@Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
Log.e("This part is downloaded", "..." + len2 + " start with: " + counter);
}
}
All logs shows that every thing is OK and file is completely downloaded. but each chunk download separate and in order. I want to download chunks Simultaneously
Upvotes: 0
Views: 64
Reputation: 2149
Instead of just call the .execute()
method of your AsyncTask, use this logic to achieve what you want:
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
new MyAsyncTask().execute(params);
}
Check more info from the official documentation of AsyncTask
Upvotes: 2