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

时间:2017-08-24 02:49:18

标签: android for-loop android-asynctask

我的值大于1,因此我计划为每个值执行for循环。问题是for循环是循环/继续,即使AsyncTask还没有完成。

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

2 个答案:

答案 0 :(得分:1)

正如@ 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);
        }
    }
}

希望有所帮助。

答案 1 :(得分:1)

我的解决方案有点远,但我想我的工作。

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访问的全局单例变量。