2012-12-26 47 views
0

我试图用各种for循环下载几个png文件。请问在我的情况下,我如何使用publishProgress()方法?如何计算下载多个文件的AsyncTask的进度

这里是我的代码:

protected String doInBackground(String... params) { 


    for(PlaceDetails place : places){ 
     for(int v = 14; v <=16; v++){ 
      for (int y = 0; y <= placeBottomLeft.getYTile(); y++){ 
       for(int x = placeTopLeft.getXTile(); x <= placeBottomRight.getXTile(); x++){ 
        try { 
         //Download some stuff here 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 

      } 
     } 
    } 

    for (int w = zoom -1 ; w <= zoom+1; w++){ 
     for (int y = topLeft.getYTile(); y <= bottomLeft.getYTile(); y++){ 
      for(int x = topLeft.getXTile(); x <= bottomRight.getXTile(); x++){ 
       try { 
        //Download some stuff here again 
       } catch (Exception e) { 
        Log.e("URL::: ERROR", e.getMessage()); 
        e.printStackTrace(); 
       } 
      } 

     } 
    } 
    return null; 
} 

正如你所看到的,我想下载的东西,在2个独立的在doInBackground方法循环。然而,我见过的大多数例子只是让线程休眠,并将for循环计数器号用作publishProgress()方法的整数。在这种情况下我应该如何使用它?谢谢!

编辑:

为了进一步澄清,我想知道是否有可能有最新进展情况,包括事情在onPostExecuteMethod()完成。

protected void onPostExecute (String result){ 
    File newFileDir = new File(Environment.getExternalStorageDirectory().toString() + "/Qiito Offline/offlineMap"); 
    File fileDir = new File(Environment.getExternalStorageDirectory().toString() 
      + "/test"); 
    try { 
     Log.e("Starting :: ", newFileDir.getPath()); 
     File newFile = new File(newFileDir, "" + tID + ".zip"); 
     newFileDir.mkdirs(); 
     OutputStream output = new FileOutputStream(newFile); 
     ZipOutputStream zipoutput = new ZipOutputStream(output); 
     zip(fileDir, fileDir, zipoutput); 
     zipoutput.close(); 
     output.close(); 
     deleteDirectory(fileDir); 
     mNotificationHelper.completed(); //method I used for my NotificationHelper to inform that the entire process is completed 
    } catch (IOException excep) { 
     Log.e("ERROR!!" , excep.getLocalizedMessage()); 
    } 
} 

在postExecute()中,我试图压缩另一个文件夹中的png文件,然后删除所有的png文件。进度条是否也可以包含这一点?否则,我只会跟踪下载png文件。

+0

你想分开显示不同文件中的所有文件一起进步或者进步? –

+0

如果可能,我想直接从onPreExecute()开始显示它的进度,直到在onPostExecute()完成为止。 – lyk

回答

1

写代码doInBackground()

int totalCount = 0; // total images count 
int counter = 0; // current downloaded files count 

// images - ArrayList with images 
totalCount = images.size(); 

// download and publish progress 
    int imagesCount = images.size(); 
    for (int i = 0; i < imagesCount; i++) { 
      // download image 

      publishProgress((int) ((counter++/(float) totalCount) * 100)); 
    } 
+0

感谢您的支持!问题是,图像的数量是动态的,因此我不会说。每个for循环的计数器不是一个固定的数字... – lyk

+0

可以计算循环之前的所有图像计数? –

+0

我想这可能是可能的,但我想如果有更好的方法,因为之前的计算需要经历所有循环两次,而且我不确定是否会减慢整个过程。我还更新了我的问题,想知道是否可以计算PostExecute过程,这是否会使问题复杂化? – lyk

相关问题