Android:如何在AsyncTask完成后使For Loop继续循环(onPostExecute)



我的值大于 1,所以我计划为每个值创建一个 for 循环来执行。问题是 for 循环正在循环/继续,即使 AsyncTask 尚未完成。

异步任务类

public class Server extends AsyncTask<JSONObject, Void, Void> {
@Override
protected Void doInBackground(JSONObject... params) {
.........
}
@Override
protected void onPostExecute(Void result) {
.........
}
}

活动

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
for(int i=0; i<10; i++){
Server  myServer = new Server();
myServer.execute(i);
}
}

正如@cricket_007所评论的那样,循环不会等待,因为AsyncTask是异步的,因此循环继续而不等待AsyncTask完成。因此,正如我理解你的目的,你需要做这样的事情。

您需要定义这样的接口。

public interface ResponseListener {
void responseReceiver();
}

现在像这样修改您的AsyncTask

public class Server extends AsyncTask<JSONObject, Void, Void> {
public ResponseListener responseListener;
@Override
protected Void doInBackground(JSONObject... params) {
// .........
}
@Override
protected void onPostExecute(Void result) {
// ......... Other code
// Now here's the callback function to the main activity.
responseListener.responseReceiver(); 
}
}

现在从您的活动中,您需要做这样的事情。

public class YourActivity extends Activity implements HttpResponseListener {
public int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
Server  myServer = new Server();
myServer.responseListener = this;
myServer.execute(i);
}
// Callback method implementation
@Override
public void responseReceiver() {
// This is the callback function and it gets called when one AsyncTask finishes.
// Increase the count here and keep track of how many times the AsyncTask has been executed.
// Do something 
count++; 
// Now call the next AsyncTask again if the count haven't reach 10 already
if(count <= 10) {
Server  myServer = new Server();
myServer.responseListener = this;
myServer.execute(i);
}
}
}

希望有帮助。

我的解决方案有点长,但我想可以完成工作。

static Boolean ASYNC_TASK_FINISHED;    
for(int i=0; i<10; i++){
ASYNC_TASK_FINISHED = false;
Server  myServer = new Server();
myServer.execute(i);
while(!ASYNC_TASK_FINISHED){ }
}

然后在你的AsyncTask

@Override
protected void onPostExecute(Void result) {
...
ASYNC_TASK_FINISHED = true;
}

您应该使ASYNC_TASK_FINISHED变量成为ActivityAsyncTask都可以访问的全局单例变量。

相关内容

  • 没有找到相关文章

最新更新