Java – How Android implements parallel execution for AsyncTask

How Android implements parallel execution for AsyncTask… here is a solution to the problem.

How Android implements parallel execution for AsyncTask

I need to allow multiple AsyncTask to run at the same time.
This is my AsyncTask:

 private void callAPI(String user_id) {
    new AsyncTask<Void, Void, String>() {

protected String doInBackground(Void... parameters) {

List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("user_id",    user_id));

return api.post("", params);

}//end doInBackground

protected void onPostExecute(String result) {
                Log.i(TAG + "POST() => " + result);

}//end onPostExecute
        }.execute(); end AsyncTask
      }

I’m Running-multiple-asynctasks saw an answer, but I didn’t know how to use it.
How do I implement the following code in my AsyncTask:

     @TargetApi(Build.VERSION_CODES. HONEYCOMB) // API 11
void startMyTask(AsyncTask asyncTask) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES. HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}

Solution

Create calls from AsynTask and synchronously call classes from MainActivity:

public class ApiCalling extends AsyncTask<String, Void, String>() {

protected String doInBackground(String... parameters) {

Log.d("LogTag","starting Async Task:"+parameters[0]);

List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user_id",    user_id));

return api.post("", params);

}//end doInBackground

protected void onPostExecute(String result) {
            Log.i(TAG + "POST() => " + result);

}//end onPostExecute
    }.execute(); end AsyncTask

From your MainActivity onCreate():

ApiCalling mObj = new ApiCalling();
mObj.execute("call 1");

/* if the task inside asyn task if long, then better to get new reference of Async task and execute other task */
ApiCalling mObj = new ApiCalling();
mObj.execute("call 2");

Related Problems and Solutions