0

for() 루프를 사용하여 AsyncTask에서 여러 파일을 다운로드 중입니다. 아래 코드는 정상적으로 작동하지만 각 파일은 자체 진행률 표시 줄과 단일 진행률 표시 줄로 다운로드되므로 다운로드 한 모든 파일에 대해 하나의 진행률 표시 줄 만 있으면됩니다. 아래하나의 progressbar java/Android로 여러 파일 다운로드

// ProgressDialog for downloading images 
@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
     case progress_bar_type: 
      pDialog = new ProgressDialog(this); 
      pDialog.setMessage("Downloading file. Please wait..."); 
      pDialog.setTitle("In progress..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setMax(100); 
      pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
      return pDialog; 
     default: 
      return null; 
    } 
} 

그리고는 ..

class DownloadFileFromURL extends AsyncTask<String, Integer, String> { 
     /** 
    * Before starting background thread Show Progress Bar Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     showDialog(progress_bar_type); 
    } 

    /** 
    * Downloading file in background thread 
    * */ 
    @Override 
    protected String doInBackground(String... f_url) { 
     int count; 
     try { 

      for (int i = 0; i < f_url.length; i++) { 
       URL url = new URL(f_url[i]); 
       URLConnection conection = url.openConnection(); 
       conection.connect(); 
       // getting file length 
       int lenghtOfFile = conection.getContentLength(); 

       // input stream to read file - with 8k buffer 
       InputStream input = new BufferedInputStream(
         url.openStream(), 8192); 
       System.out.println("Data::" + f_url[i]); 
       // Output stream to write file 
       OutputStream output = new FileOutputStream(
         "/sdcard/Images/" + i + ".jpg"); 

       byte data[] = new byte[1024]; 

       long total = 0; 
       int zarab=20; 

       while ((count = input.read(data)) != -1) { 
        total += count; 
        // publishing the progress.... 
        // After this onProgressUpdate will be called 
        publishProgress((int) ((total * 100)/lenghtOfFile)); 

        // writing data to file 
        output.write(data, 0, count); 
       } 

       // flushing output 
       output.flush(); 

       // closing streams 
       output.close(); 
       input.close(); 
       //cc++; 
      } 
     } catch (Exception e) { 
      Log.e("Error: ", e.getMessage()); 
     } 

     return null; 
    } 

    /** 
    * Updating progress bar 
    * */ 
    protected void onProgressUpdate(Integer... progress) { 
     // setting progress percentage 
     pDialog.setProgress(progress[0]); 
    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    @Override 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after the file was downloaded 
     dismissDialog(progress_bar_type); 

     // Displaying downloaded image into image view 
     // Reading image path from sdcard 
     //String imagePath = Environment.getExternalStorageDirectory() 
     //  .toString() + "/downloaded.jpg"; 
     // setting downloaded into image view 
     // my_image.setImageDrawable(Drawable.createFromPath(imagePath)); 
    } 

} 

다운로드 파일에 대한 AsyncTask를 또는 파일의 번호에 대한 ProgressBar의 쇼와 업그레이드 lenghtOfFile 대신 의미 경우에도 대체하고 도움이 해결책이 될 것입니다. 도움이 될 것입니다.

당신은 사전에 알고

가짜 진행률 표시 줄 방법을 다운로드 할 필요가 얼마나 많은 파일, 당신은에 ProgressDialog 총량을 설정할 수 있습니다

+0

안녕하세요, 귀하의 작업 코드를 공유 할 수 있습니까? 미리 감사드립니다. –

+0

@MuhammadSufiyan 제 작업 코드는 다음과 같습니다. 답변, 여기에서 코드를 공유 할 수 있습니다. 가능한 경우 도와 드리겠습니다. 문제를 해결하십시오. –

+0

감사합니다. 내 문제는 내 댓글의 같은 날에도 해결되었습니다 .. 문제가 해결되었음을 알리는 것도 좋습니다. –

답변

1

나는 당신이 두 가지 옵션이 있습니다 생각 다운로드 할 파일 수. 이것은 크기가 작고 비슷한 파일들과 잘 작동하며 사용자에게 무슨 일이 일어나고 있는지에 대한 좋은 피드백을줍니다.

// you can modify the max value of a ProgressDialog, we modify it 
// to prevent unnecessary rounding math. 
// In the configuration set the max value of the ProgressDialog to an int with 
pDialog.setMax(urls.length); 

for (int i = 0; i < urls.length; i++) { 
    // launch HTTP request and save the file 
    //... 
    // your code 
    //... 

    //advance one step each completed download 
    publishProgress(); 
} 

/** 
* Updating progress bar 
*/ 
protected void onProgressUpdate(Integer... progress) { 
    pDialog.incrementProgressBy(1); 
} 

실제 진행률 표시 줄의 접근 방식은

당신은 사전에 알고 다운로드하는 데 필요한 모든 파일의 총 길이가 필요합니다. 예를 들어 별도의 파일을 다운로드하기 전에 총 길이를 바이트 단위로 제공하는 다른 모든 서비스보다 먼저 호출 할 별도의 REST API를 만들 수 있습니다. 이렇게하면 이미 다운로드 한 총 바이트 수에 따라 전체 ProgressDialog 길이를 주기적으로 업데이트 할 수 있습니다.

+0

좋은 단서, 당신은 100/urls.length를 뛰어 넘으려고했는데 어떻게 보호 된 void onProgressUpdate (정수 ... 진행) { // 설정 진행률 백분율 pDialog.setProgress (progress [0]); } –

+0

답변을 업데이트했습니다 – MatPag

+0

답장을 보내 주셔서 감사합니다. 하지만 코드를 구현함으로써 첫 번째 파일을 다운로드 한 후 progressbar가 100 %로 점프하고 여전히 100 %로 유지됩니다. 각 파일 다운로드 후에 progressbar가 업데이트/진행 중이 지 않습니다. –