【问题标题】:Download multiple files with one progressbar java / Android用一个进度条下载多个文件 java / Android
【发布时间】:2018-06-09 23:04:06
【问题描述】:

我在 for() 循环的帮助下在 AsyncTask 中下载多个文件。 下面的代码工作正常,但每个下载的文件都有自己的单个进度条,我想要所有下载的文件只有一个进度条。

// 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;
    }
}

下面是下载文件的AsyncTask..

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));
    }

}

或者,如果 Progressbar 显示和升级关于 Nos of Files 意味着代替 lenghtOfFile,它也将是替代且有用的解决方案。 任何帮助将不胜感激。

【问题讨论】:

  • 嗨,你能分享你的工作代码吗,我也在同样的问题上苦苦挣扎,提前谢谢
  • @MuhammadSufiyan 我的工作代码与下面接受的答案相同,如果可能的话,您可以在此处分享您的代码,我会帮助您解决您的问题。
  • 谢谢,我的问题在我发表评论的同一天也得到了解决。很高兴知道你的问题也得到了解决。

标签: java android android-asynctask progress-bar android-progressbar


【解决方案1】:

我认为你有两个选择:

假进度条方法

您提前知道需要下载多少文件,可以将ProgressDialog总量设置为要下载的文件数量。这对于尺寸小且相似的文件非常有效,并且可以为用户提供有关正在发生的事情的良好反馈。

// 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 的总长度。

【讨论】:

  • 好线索,你的意思是说潜入 100/urls.length 但我如何在受保护的 void onProgressUpdate(Integer...progress) 中实现它 { // 设置进度百分比 pDialog.setProgress(progress[ 0]); }
  • 感谢您的回复。但是通过实现您的代码,进度条会在第一个文件下载后跳转到 100% 并保持在 100%,这意味着在每次文件下载后进度条不会更新/进度。
  • 您是否已将您的pDialog.setMax(100); 更改为pDialog.setMax(urls.length);?然后在您的onProgressUpdate 方法中使用pDialog.incrementProgressBy(1)。显然你需要将publishProgress()移出while循环,将它放在for循环的末尾
  • 非常感谢,问题解决了你是最棒的。上帝保佑你,也对不起我的英语和关于java的一周知识。您指出每一步以了解我并帮助我。再次感谢
  • 如果对您有用,请接受答案。它可以帮助其他人搜索相同的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2022-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多