我尝试使用各种for循环下载几个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循环中下载内容。然而,我见过的大多数示例只是使线程休眠并使用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 :(得分: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));
}