使用一个进度条下载多个文件 java/Android [英] Download multiple files with one progressbar java / Android

查看:56
本文介绍了使用一个进度条下载多个文件 java/Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

//用于下载图像的ProgressDialog@覆盖受保护的对话框 onCreateDialog(int id) {开关(ID){案例progress_bar_type:pDialog = new ProgressDialog(this);pDialog.setMessage("正在下载文件,请稍候...");pDialog.setTitle("进行中...");pDialog.setIndeterminate(false);pDialog.setMax(100);pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);pDialog.setCancelable(true);pDialog.show();返回 pDialog;默认:返回空;}}

下面是下载文件的AsyncTask..

class DownloadFileFromURL extends AsyncTask{/*** 启动后台线程前显示进度条对话框* */@覆盖受保护的无效 onPreExecute() {super.onPreExecute();showDialog(progress_bar_type);}/*** 在后台线程下载文件* */@覆盖受保护的字符串 doInBackground(String... f_url) {整数计数;尝试 {for (int i = 0; i < f_url.length; i++) {URL url = 新 URL(f_url[i]);URLConnection 连接 = url.openConnection();连接.connect();//获取文件长度int lenghtOfFile = conction.getContentLength();//读取文件的输入流 - 8k 缓冲区InputStream 输入 = 新的 BufferedInputStream(url.openStream(), 8192);System.out.println("数据::" + f_url[i]);//输出流写入文件OutputStream 输出 = 新 FileOutputStream("/sdcard/Images/" + i + ".jpg");字节数据[] = 新字节[1024];总长 = 0;int zarab=20;while ((count = input.read(data)) != -1) {总数 += 计数;//发布进度....//在此之后 onProgressUpdate 将被调用publishProgress((int) ((total * 100)/lenghtOfFile));//将数据写入文件output.write(data, 0, count);}//刷新输出输出.flush();//关闭流输出关闭();input.close();//cc++;}} 捕获(异常 e){Log.e("错误:", e.getMessage());}返回空;}/*** 更新进度条* */protected void onProgressUpdate(Integer... progress) {//设置进度百分比pDialog.setProgress(progress[0]);}/*** 完成后台任务后关闭进度对话框* **/@覆盖protected void onPostExecute(String file_url) {//文件下载后关闭对话框解雇对话框(进度条类型);//将下载的图像显示到图像视图中//从sdcard读取图片路径//String imagePath = Environment.getExternalStorageDirectory()//.toString() + "/downloaded.jpg";//设置下载到图像视图//my_image.setImageDrawable(Drawable.createFromPath(imagePath));}}

或者,如果 Progressbar 显示和升级关于文件数意味着而不是 lenghtOfFile 它也将是替代和有用的解决方案.任何帮助将不胜感激.

解决方案

我认为你有两个选择:

<块引用>

假进度条方法

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

//可以修改一个ProgressDialog的最大值,我们修改//防止不必要的舍入数学.//在配置中将 ProgressDialog 的最大值设置为 intpDialog.setMax(urls.length);for (int i = 0; i < urls.length; i++) {//发起 HTTP 请求并保存文件//...//你的代码//...//每完成一次下载前进一步发布进度();}/*** 更新进度条*/protected void onProgressUpdate(Integer... progress) {pDialog.incrementProgressBy(1);}

<小时><块引用>

真正的进度条方法

您需要提前知道您需要下载的所有文件的总长度.例如,您可以创建一个单独的 REST API 以在开始下载每个单独文件之前为您提供以字节为单位的总长度的所有其他内容之前调用.这样,您可以根据已下载的总字节数定期更新 ProgressDialog 总长度.

I am downloading multiple files in an AsyncTask with the help of for() loop. 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..

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. Any help will be highly appreciated.

解决方案

I think you have 2 options:

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. 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. In this way, you can periodically update the total ProgressDialog length accordingly to the total bytes you have already downloaded.

这篇关于使用一个进度条下载多个文件 java/Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆