2015-10-15 4 views
0

Привет, Мне нужно показать общий прогресс AsyncTask. Я хочу показать ProgressBar или ProgressDialog для загрузки, но я знаю, что делать, я знаю, как показывать диалог, но только когда я загружаю один файл и как это сделать, когда у меня есть много файлов для загрузки. Может кто-нибудь помочь ????ProgressDialog AsyncTask

Вот мой AyncTaskClass

public class DownloadProgramTask extends AsyncTask<String, Integer, String> { 

    @Override 
    protected String doInBackground(String... sUrl) { 
     InputStream input = null; 
     OutputStream output = null; 
     HttpURLConnection connection = null; 
     try { 
      URL url = new URL(sUrl[0]); 
      String path = sUrl[1]; 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 

      // expect HTTP 200 OK, so we don't mistakenly save error report 
      // instead of the file 
      if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
       return "Server returned HTTP " + connection.getResponseCode() 
         + " " + connection.getResponseMessage(); 
      } 

      // this will be useful to display download percentage 
      // might be -1: server did not report the length 
      int fileLength = connection.getContentLength(); 

      // download the file 
      input = connection.getInputStream(); 
      output = new FileOutputStream(path); 

      byte data[] = new byte[4096]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       // allow canceling with back button 
       if (isCancelled()) { 
        input.close(); 
        return null; 
       } 
       total += count; 
       // publishing the progress.... 
       if (fileLength > 0) // only if total length is known 
        publishProgress((int) (total * 100/fileLength)); 
       output.write(data, 0, count); 
      } 
     } catch (Exception e) { 
      return e.toString(); 
     } finally { 
      try { 
       if (output != null) 
        output.close(); 
       if (input != null) 
        input.close(); 
      } catch (IOException ignored) { 
      } 

      if (connection != null) 
       connection.disconnect(); 
     } 
     return null; 
    } 


} 

И я создаю новый экземпляр этого класса для каждого выполнение,

File voiceFile = new File(dirVoice, a.getPose_id() + ".mp3"); 

      if (!voiceFile.exists()) { 
       voiceList.add(a.getVoice()); 
       new DownloadProgramTask().execute(MYurl.BASE_URL + a.getVoice(), voiceFile.getPath()); 
       Log.e("LINK", MYurl.BASE_URL + a.getVoice()); 
       Log.e("Path voice", "" + voiceFile.getPath()); 

      } 

      File imgLargeFile = new File(dirImageLarge, a.getId() + ".png"); 

      if (!imgLargeFile.exists()) { 
       imgLargeList.add(a.getVoice()); 
       new DownloadProgramTask().execute(MYurl.BASE_URL + "/" + a.getImgLarge(), imgLargeFile.getPath()); 
      } 
+1

publishProgress и onProgressUpdate вещи, чтобы Google для – ligi

+0

Возможный дубликат [Загрузить файл с Android, и показывая прогресс в ProgressDialog] (http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog) – Distwo

+0

Пример 'onProgressUpdate() 'в [Android Docs] (http://developer.android.com/reference/android/os/AsyncTask.html) так же хорош как любой. – PPartisan

ответ

0

вы можете использовать перекрытый метод OnProgressUpdate из асинхронной задачи. звоните publishProgress в doingBackground из AsyncTask с interger

что-то вроде этого ..

@Override

protected void onProgressUpdate(Integer... values) { 
     super.onProgressUpdate(values); 
     Log.i("makemachine", "onProgressUpdate(): " + 
     percentBar.setProgress((values[0] * 2) + "%"); 

    } 
+0

Я показываю только для одного исполнения, но как показать прогресс всех. Или, может быть, я могу запустить каждый запуск в очереди и показать весь ход очереди? – nik

+0

Я думаю, что вы можете запускать каждый запуск в очереди и onpostexecute() каждого downloadTask, вы можете публиковать Progress для обновления строки выполнения пользовательского интерфейса –

Смежные вопросы