Search code examples
androidandroid-asynctaskparallel-processingexecutor

Same AsyncTask for Parallel execution


I have an AsyncTask as public class like below,

public class FetchFromTCWebTask extends AsyncTask<String, Void, String> {
MainActivity mainActivity;
int requestId;
private final static String DEBUG_TAG = "FetchFromTCWebTask";

FetchFromTCWebTask(MainActivity activity, int id) {
    mainActivity = activity;
    requestId = id;
}

@Override
protected String doInBackground(String[] urls) {
    // params comes from the execute() call: params[0] is the url.
    try {
        return downloadUrl(urls[0]);
    } catch (IOException e) {
        return "Unable to retrieve web page. URL may be invalid.";
    }
}

@Override
protected void onPostExecute(String result) {
    mainActivity.loadFinished(result);
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}

public interface UIListner {
    public void loadFinished(String result);

    public void loading(int progress);
}

}

Now i want to call it as

(new FetchFromTCWebTask(actviity,1)).execute(url);
(new FetchFromTCWebTask(actviity,2)).execute(url);
(new FetchFromTCWebTask(actviity,3)).execute(url);

Now My Question is , there any way to do like it in parallel and get back the results separately for 1,2 and 3 ? if yes then how ?


Solution

  • Use a thread pool to achieve this.

    (new FetchFromTCWebTask(actviity, 1)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url)
    (new FetchFromTCWebTask(actviity, 2)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url)
    (new FetchFromTCWebTask(actviity, 3)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url)
    

    ExecuteOnExecutor


    Since I figure you're about to ask me how to write this (for the twentieth time), here's a small example. I omitted some parts since they're not relevant. This is how you would send the id back to the activity to distinguish between them. If you needed to do different tasks inside of onPostExecute then just use a switch/case statement.

    public class FetchFromTCWebTask extends AsyncTask<String, Void, String>
    {
        MainActivity mainActivity;
        int requestId;
    
        FetchFromTCWebTask(MainActivity activity, int id)
        {
            mainActivity = activity;
            requestId = id;
        }
    
        ...
    
        @Override
        protected void onPostExecute(String result)
        {
            mainActivity.loadFinished(result, requestId);
        }
    
        public interface UIListner
        {
            public void loadFinished(String result, int id);
            public void loading(int progress);
        }
    }