等待循环中调用的所有AsyncTask都完成了?

时间:2015-03-25 09:55:12

标签: android android-asynctask

我在asyncTask的onPostExecute()循环中调用异步任务。我希望控件等到所有任务的响应都没有收到,因为我在单个arrayList中收集响应,我必须在循环中调用的所有asyncTasks完成后传递一个回调方法。

我避免使用AsyncTask.get(),因为它阻止了主线程。

public class CallServerAsync extends AsyncTask<AsyncHttpRequestBo, Void, ArrayList<ArrayList<AsyncHttpRequestBo>>> implements PlatwareResponseListener {
PlatwareClientCommonUtils clientCommonFunctions;
Context context;
String url;
PlatwareResponseListener listener;
private ProgressDialog progressDialog;
ArrayList<AsyncHttpResponseBo> processResponseList = null;
ArrayList<AsyncHttpResponseBo> responseList = null;

public CallServerAsync(Context context, PlatwareResponseListener listener) {
    this.context = context;
    clientCommonFunctions = new PlatwareClientCommonUtils(context);
    url = clientCommonFunctions.getServerUrlPrimary();
    this.listener = listener;
    responseList = new ArrayList<AsyncHttpResponseBo>();
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = ProgressDialog.show(context, "Please wait", "Downloading...");
}

@Override
protected ArrayList<ArrayList<AsyncHttpRequestBo>> doInBackground(AsyncHttpRequestBo... params) {

    ArrayList<ArrayList<AsyncHttpRequestBo>> requestLists = clientCommonFunctions.generateRequestList(params);
    return requestLists;
}

@Override
protected void onPostExecute(ArrayList<ArrayList<AsyncHttpRequestBo>> result) {

    for (ArrayList<AsyncHttpRequestBo> httpRequestList : result) {
        CallserverSubAsync callserverSubAsync = new CallserverSubAsync(context, this);
        callserverSubAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, httpRequestList);
        // ArrayList<AsyncHttpResponseBo> processResponseList = null;
        // try {
        // processResponseList = callserverSubAsync.get();
        // } catch (InterruptedException e) {
        // e.printStackTrace();
        // } catch (ExecutionException e) {
        // e.printStackTrace();
        // }

    }
    listener.onAsyncTaskCompleted(responseList, listener);
    progressDialog.dismiss();
    super.onPostExecute(result);
}

@Override
protected void onCancelled() {
    progressDialog.dismiss();
    super.onCancelled();
}

@Override
public void onAsyncTaskCompleted(ArrayList<AsyncHttpResponseBo> responseList, PlatwareResponseListener listener) {
    if (listener instanceof CallServerAsync) {
        processResponseList = responseList;
        for (AsyncHttpResponseBo responseBo : processResponseList) {
            this.responseList.add(responseBo);
        }
    }

}

0 个答案:

没有答案