2016-03-05 21 views
0

我有一個程序,點擊一個按鈕,點擊時,4個下載應同時執行。我用ASyncTask類此目的,for迭代:幾次同時使用一個ASyncTask

for(int i=0;i<downloadCounts;i++){ 
new DownloadTask().execute(url[i]); 
} 

但在運行時,只有一個下載執行,所有4個progressbars表明,單次下載。 我想同時下載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); 
    } 
} 

所有日誌表明,每一件事情是確定,文件下載完畢。但是每個塊下載都是分開的和按順序的。我想下載塊同時

+1

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); } else { new MyAsyncTask().execute(params); } 

檢查的詳細信息根據您的代碼,在我看來,應該開始四個下載。但是,請張貼更多的代碼,以便我們提供幫助。 –

+0

@RuchiraRandana更多詳細信息增加 –

回答

2

而不是隻打電話給你的AsyncTask的.execute()方法,用這個邏輯來實現你想要的:從official documentation of AsyncTask

+0

這是偉大的工作。謝謝。但我所有的進度條都顯示相同的百分比。你知道任何決心嗎? –

+0

但這不正確嗎? –

+0

是的。 AsyncTasks工作非常好。但我不能爲這些分配獨立的'ProgressBar.setProgress(int)'。 –