代码之家  ›  专栏  ›  技术社区  ›  Ambreen Khan

使用一个progressbar java/Android下载多个文件

  •  0
  • Ambreen Khan  · 技术社区  · 7 年前

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

    下面是下载文件的异步任务。。

    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显示并升级文件数量,而不是长度文件,那么它也将是另一种有用的解决方案。 我们将非常感谢您的帮助。

    1 回复  |  直到 7 年前
        1
  •  1
  •   MatPag    7 年前

    我认为您有两种选择:

    假进度条方法

    您提前知道需要下载多少文件,可以设置 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,在开始下载每个单独的文件之前先调用它,这样就可以得到总长度(以字节为单位)。通过这种方式,您可以定期更新总数 进度对话框 与已下载的总字节数相对应的长度。