【发布时间】:2015-12-20 12:17:48
【问题描述】:
实际上我想要做的是在循环中多次调用 asyncTask。因此,第一次 asyncTask 将立即启动,从第二次开始,它将检查 AsyncTask 是否已完成 - 如果完成,则再次使用不同的值调用它。
以下是我的活动代码:
在 onCreate() 中
btnUpload.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
count_response = 0;
newUploadWithSeparate();
}
});
newUploadWithSeparate() 方法:
private void newUploadWithSeparate()
{
responseString_concat = "";
if(filePath.length > 0)
{
for(int i=0;i<filePath.length;i++)
{
count_response = i;
if(i == 0)
{
uploadAsync.execute(filePath[0]);
mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
String s=(String)msg.obj;
Log.d("logIMEI","\n Response from Asynctask: " + s);
str_response_fromAsync = s;
}
};
}
else
{
uploadAsync.getStatus();
while(uploadAsync.getStatus() == AsyncTask.Status.RUNNING) // this while loop is just to keep the loop value waitining for finishing the asyncTask
{
int rx = 0;
}
if(uploadAsync.getStatus() != AsyncTask.Status.RUNNING)
{
if(uploadAsync.getStatus() == AsyncTask.Status.FINISHED)
{
if(str_response_fromAsync != "" || !str_response_fromAsync.equals("") || !str_response_fromAsync.isEmpty())
{
uploadAsync.execute(filePath[i]);
x = i;
mHandler = new Handler() {
@Override public void handleMessage(Message msg)
{
String s=(String)msg.obj;
Log.d("logIMEI","\n Response from Asynctask_" + x + ": " + s);
str_response_fromAsync = s;
}
};
}
}
}
}
}
}
}
还有 asyncTask:
private class UploadFileToServer extends AsyncTask<String, Integer, String>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(String... params)
{
return uploadFile(params[0]);
}
private String uploadFile(String pr)
{
//inside here calling webservice and getting a response string as result.
MyWebsrvcClass mycls = new MyWebsrvcClass();
return responseString_concat = mycls.Call(xxx,yyy) ;
}
@Override
protected void onPostExecute(String result)
{
Log.d("logIMEI" , "\n count_response : "+ count_response + " fileprath_len : " + filePath.length);
Message msg=new Message();
msg.obj=result.toString();
mHandler.sendMessage(msg);
super.onPostExecute(result);
}
}
现在的问题是它没有按预期工作。当i 的值第一次等于0 时,AsyncTask 被调用,之后它不再被调用。
另外,当第一次调用AsyncTask 时,它仍然没有直接进入onPostExecute()。当循环完全结束并且newUploadWithSeparate() 方法结束时,onPostExecute() 正在工作。
使用AsyncTask inside loop 完成这项工作的任何解决方案或任何其他方式?
【问题讨论】:
-
您可以将所有内容放入doInBackground 方法中,使用publishProgress() 返回服务器结果,然后让线程休眠。或者使用服务。 developer.android.com/guide/components/services.html
-
您正在使用同一个 asynctask 实例,并对其多次调用“执行”。您应该在每次迭代中创建一个新的 asynctask 实例。
-
您可以传递
array的params并让task处理它们,使用publishProgress发布更新