我有一个单击按钮的程序,点击时,4个下载应该同时执行。为此,我使用ASyncTask
类与for
迭代器:
for(int i=0;i<downloadCounts;i++){
new DownloadTask().execute(url[i]);
}
但在运行中,只执行了一次下载,所有4个进度条显示单次下载。 我想同时下载4个下载。我怎么办?
了解更多详情,我的下载管理器,根据文件大小获取一个链接并将其分为4个块。然后使用上面的for
迭代器,命令它使用此类运行4部分下载:
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);
}
}
所有日志都显示所有内容都正常,文件已完全下载。但每个块下载分开并按顺序排列。我想同时下载块
答案 0 :(得分:2)
不要只调用AsyncTask的.execute()
方法,而是使用这个逻辑来实现你想要的:
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
new MyAsyncTask().execute(params);
}
中的更多信息