使用一个进度条java/android下载多个文件(代码片段)

author author     2022-12-28     649

关键词:

我在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显示和升级相对于文件数而不是lenghtOfFile,它也将是替代和有用的解决方案。任何帮助将受到高度赞赏。

答案

我想你有两个选择:

虚假的进度条方法

您事先知道需要下载多少文件,您可以将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长度。

iOS,Swift:串行下载多个文件并将所有文件的单个进度条显示为一个进度

...ogress【发布时间】:2020-01-2307:25:12【问题描述】:我正在使用我的ios(swift4)应用程序中的Alamofire下载zip文件。我可以使用Alamofir 查看详情

使用请求通过 http 下载文件时的进度条

】使用请求通过http下载文件时的进度条【英文标题】:ProgressBarwhiledownloadfileoverhttpwithRequests【发布时间】:2016-10-0102:32:51【问题描述】:我需要下载一个相当大的(~200MB)文件。我想出了如何使用here下载和保存文件。最好有一个... 查看详情

具有多个不同输入的文件上传进度条(MVC)

...,用于文件上传进度条,它可以100%正常工作(因为您只使用一个表单输入)。我的情况是我需要将一个文件和4个其他输入(如文本)传递给控制器​​操作。 查看详情

使用newxmlhttprequest()制作下载文件进度条

mui进度控件使用方法:检查当前容器(container控件)自身是否包含.mui-progressbar类:当前容器包含.mui-progressbar类,则以当前容器为目标控件,直接显示进度;否则,检查当前容器的直接孩子节点是否包含.mui-progressbar类,若存在,则... 查看详情

显示下载进度条

...】:2021-10-2604:24:50【问题描述】:在我的应用程序中,我使用执行器服务从url下载文件。现在我想添加一个水平进度条来显示下载进度。但我面临错误。如何在不使用异步任务的情况下在此代码中添加进度条?privateclassExecutorServ... 查看详情

NSURLSession 下载任务 - 进度条问题

...,我必须在其中下载视频,下载后我将显示它们。我正在使用NSURLSession下载它。问题在进度条中。当我开始下载第四个文件时,我可以通过进度条正确下载前两个或三个文件,进度条没有正确更新,但文件与最后删除的 查看详情

在 Xamarin Forms 中下载带有进度条的文件

...【发布时间】:2015-08-1813:32:33【问题描述】:我正在尝试使用下载进度条在XamarinForms(PCL,因此WebClient不可用)中创建一个下载页面。我使用了来自Xamarin的以下信息,但没有成功:http://developer.xamarin.com/recipe 查看详情

使用 AFNetworking 计算下载多个文件的总进度

】使用AFNetworking计算下载多个文件的总进度【英文标题】:calculatingtotalprogressofdownloadingmultiplefilewithAFNetworking【发布时间】:2014-09-0713:57:16【问题描述】:我想下载多个文件,然后向用户显示总进度。但问题就在这里,我不知道... 查看详情

php使用进度条下载php/curl文件(代码片段)

查看详情

多个 Celery 进度条

...2018-03-2202:28:58【问题描述】:问题我有一个Django站点,它使用Celery+RabbitMQ作为长期运行任务的任务队列。我将结果存储在Redis中。我已经能够使用Celery的update_state在引导进度条中显示一项任务的进度,并通过按钮向RedisDB进行ajax... 查看详情

将进度条添加到下载文件[重复]

...【发布时间】:2018-07-2422:06:42【问题描述】:我正在实现一个ViewController来显示以前从我的服务器下载并存储在设备本地的PDF,它可以正常工作,但是下载PDF需要太多时间,我想实现一个progress-bar。我的代码如下,我尝试在其中... 查看详情

pythonhttp下载文件并显示下载进度条

...条。其中利用request模块下载文件可以直接下载,不需要使用open方法,例如:import urllibimport requests.packages.urllib3requests.packages.urllib3.disable_warnings()url&n 查看详情

从服务器下载文件时进度条卡在 0%?

...布时间】:2016-12-2422:23:53【问题描述】:我正在创建一个Android应用程序来下载一个mp3文件服务器。下载工作正常。但是ProgressBar是下载时卡在0%...MainActivity.javapublicclassMainActivityexte 查看详情

像在 WhatsApp 中一样加载多个图像进度条

...显示多个进度条。以及完成的进度条隐藏进度条。我尝试使用异步任务执行此操作,但没有获得确切的解决方案,并且代表也习惯这样做。没有得到确切的解决方案。这是我的代码主要活动publi 查看详情

绑定多个下载进度

...:2015-12-1610:20:02【问题描述】:我在ObservableCollection中有一个DownloadOperation列表,并且该变量具有Progress.TotalBytesToReceive和Progress.BytesReceived属性。当我尝试将此属性绑定到进度条的最大值和值时,它给了我绑定表达式错误属 查看详情

为多个文件下载添加子进度

...时间】:2016-02-0704:47:51【问题描述】:我正在我的项目中使用AFNetworking3.0下载多个文件。我想显示所有文件的单个下载进度。我将每个文件下载的每个子进度添加到父进度中。但它不起作用,应用程序崩溃了。我收到了错误-Termi... 查看详情

水平进度条不适用于 Asynctask Android 下载文件?

】水平进度条不适用于AsynctaskAndroid下载文件?【英文标题】:HorizontalProgressBarNotWorkinginAsynctaskAndroidForDownloadfile?【发布时间】:2014-07-2417:50:27【问题描述】:我正在尝试使用Asynctask显示水平进度条,但它不适合我。它不是显示百... 查看详情

afhttpsessionmanager下载文件及下载中进度条处理,进度条处理需要特别注意,要加载nsrunloop中

 1.下载文件和进度条处理代码-(void)timer:(NSTimer*)timer{//另一个View中进度条progress属性赋值_downloadView.progress=self.pressing;if(self.pressing>=1.0){[timerinvalidate];}}-(void)downloadWithUrlString:(NSString*)url 查看详情