且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

下载多个文件一个接一个使用AsyncTask的?

更新时间:2023-01-08 16:29:05

如果我理解正确的话,你不想一(连续)来下载同恬E(同时)中的所有文件,但之一。 为了做到这一点建立与URL的字符串数组下载,并调用执行()与该阵列。

  

例:假设你的 DownloadFileAsync 预计字符串作为   参数,它的 doInBackground方法,你会打电话来:

 新DownloadFileAsync()执行(URL1,URL2,URL3,url4,VIDEO1,VIDEO2,VIDEO3,VIDEO4)。
 

I'm trying to download multiple files one by one (file is downloaded, we start downloading the next file). Using this method I can keep track of the files being downloaded. The problem is that I'm using the following code for executing a Task:

                File file = null;                
                for(int i=0; i< videos.length; i++) {
                     file = new File(root.getPath() + videos[i]);
                     boolean exists = file.exists();
                     if(exists){
                         //tv.append("\n\n"+fileNames[i]+" already exists");
                         continue;
                     }
                     else {
                         currentFile = videos[i];
                         new DownloadFileAsync().execute(videoURL+videos[i],videos[i]);            

                     }
                     file = null;
                }

As you can see, I call new DownloadFileAsync().execute(videoURL+videos[i],videos[i]); in a loop which obviously start a task for each of the files and downloads them simultaneously.

My question is: How can I run execute the task for a specific file, check if it has been downloaded- if yes, proceed with next file by executing a task for it?

If I understand correctly, you do not want to download all the files at the same tim e(simultaneously) but one by one (serially). In order to do so build a String array with the URLs to download, and call execute() with that array.

Example: Assuming that your DownloadFileAsync expects String as a parameter to it's doInBackground method, you would call to:

new DownloadFileAsync().execute(url1, url2, url3, url4, video1, video2, video3, video4);