java - java/Android 一个进度条下载多个文件

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

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

}

或者,如果进度条显示并根据文件数量进行升级,那么它也将是替代且有用的解决方案,而不是文件长度。 任何帮助将不胜感激。

最佳答案

我认为你有两个选择:

The fake progress bar approach

您事先知道需要下载多少个文件,您可以将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);
}
<小时/>

The real progress bar approach

您需要提前知道需要下载的所有文件的总长度。例如,您可以创建一个单独的 REST API 在其他所有操作之前调用,这样您就可以在开始下载每个单独的文件之前获得总长度(以字节为单位)。通过这种方式,您可以根据已下载的总字节数定期更新 ProgressDialog 总长度。

关于java - java/Android 一个进度条下载多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023733/

相关文章:

java - Java Swing 的错误消息

java - Java中是否有任何内置方法可以增加字体大小?

java - 获取Android中任何文件的真实文件路径

android - 启动外部 Activity 以扫描条形码

android - 如何在Android中解析 "Error:Error: ' ' is not a valid resource name character"?

android - 进度条加载消失

java - 查找所有实现特定接口(interface)的类

java - Apache Pivot,从 Apache 孵化器到 Main,反馈?

Android 异步 Http 客户端 (loopj) 和持久性 Cookie 存储

android - onPostExecute 在 doInBackground 完成之前调用 - 异步任务