简体   繁体   English

使用一个ProgressBar Java / Android下载多个文件

[英]Download multiple files with one progressbar java / Android

I am downloading multiple files in an AsyncTask with the help of for() loop. 我正在for()循环的帮助下在AsyncTask中下载多个文件。 Below code works fine but each file downloaded with its own and single progress bar, I want only one progress bar for all the downloaded files. 下面的代码可以正常工作,但是每个下载的文件都有自己的单个进度条,我只希望所有下载文件都有一个进度条。

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

And below is the AsyncTask for download files.. 下面是用于下载文件的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));
    }

}

Or if Progressbar shows and upgrades with respect to Nos of Files means instead of lenghtOfFile it will also be alternate and helpful solution. 或者,如果进度栏显示并针对“文件数”进行了升级,则表示该方法不是替代lenghtOfFile,也将是替代且有用的解决方案。 Any help will be highly appreciated. 任何帮助将不胜感激。

I think you have 2 options: 我认为您有2种选择:

The fake progress bar approach 假进度条方法

You know in advance how many files you need to download, you can set the ProgressDialog total amount to the number of files to download. 您预先知道需要下载多少个文件,可以将ProgressDialog总数设置为要下载的文件数。 This works pretty well with files which are small and similar in dimensions and gives the user a good feedback about what's going on. 这对于尺寸较小且尺寸相似的文件非常有效,并且可以为用户提供有关发生情况的良好反馈。

// 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 真正的进度条方法

You need to know in advance the total length of all the files you need to download. 您需要事先知道需要下载的所有文件的总长度。 For example, you could create a separate REST API to call before everything else which give you the total length in bytes before you start to download each separate files. 例如,您可以创建一个单独的REST API,以便在开始下载每个单独的文件之前先调用所有其他内容,从而获得总长度(以字节为单位)。 In this way, you can periodically update the total ProgressDialog length accordingly to the total bytes you have already downloaded. 这样,您可以根据已下载的总字节数定期更新ProgressDialog的总长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM