如何计算下载多个文件的asynctask的进度



我正在尝试使用各种循环下载一些PNG文件。我可以问一下我如何确切使用PublishProgress()方法?

这是我的代码:

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

您可以看到,我正在尝试在Doinbackground方法中在2个单独的循环中下载内容。但是,我看到的大多数示例只会使线程睡觉,并将for循环计数器号码用作PublishProgress()方法的整数。在这种情况下,我应该如何使用它?谢谢!

编辑:

要进一步澄清,我想知道是否有可能将进度更新包括在Onpostececutemethod()中包括完成的事情。

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文件。

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

最新更新