我有一个for循环,它将在服务器上下载图像,这就是它的样子
for (int i = 0; i < sync_data.length(); i++) {
String main_link = "LINK" + folder + "/" + file_name;
FilePathname = sdCardDirectory + "/" + file_name;
DownloadFilesname(FilePathname, main_link);
index++;
p = (float) index / (float) sync_data.length();
p = p * (float) 100;
runOnUiThread(new Runnable() {
@Override
public void run() {
publishProgress((int) p);
}
});
}
/ *功能图像下载* /
public void DownloadFilesname(String filanme, String Urlname) {
try {
URL u = new URL(Urlname);
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(new File(filanme));
while ((length = dis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
}
}
我的问题是publishProgress
已经更新,即使尚未下载图像。这将导致asynctask完成,但映像仍在下载中。
如何使图像必须在增量之前下载?
答案 0 :(得分:0)
您只需在“ doInBackground()”中调用“ publishProgress()”,然后实施/覆盖
protected void onProgressUpdate(Integer... progress) {
...
}
当您调用“ publishProgress()”时,会在Ui / MainThread中调用“ onProgressUpdate()”事件(这意味着您可以使用其中的所有UI组件)