Search code examples
androidandroid-asynctaskqueuewaitrunnable

Android AsyncTask waiting/queued


I have a class extending an AsyncTask that sends messages to a WCF web service. Simple messages one by one will work fine, but if I send a message on a new thread that takes 30 seconds to complete, then midway through that I send a quick request it won't execute the AsyncTask until the long one has returned.

I thought the whole idea of AsyncTask was these two messages would run on different threads and therefore wouldn't stack?

Here is my code:

private class RunnableTask extends AsyncTask<RunnableObj, RunnableObj, RunnableObj> {
    @Override
    protected RunnableObj doInBackground(RunnableObj... params) {
        try {
            if (params[0].requestBody != (null)) {
                params[0].request.body(new JSONObject(params[0].requestBody));
            }

            params[0].request.asVoid();

            return params[0];
        }
        catch (Throwable e) {
            params[0].handler.onFailure(e);
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(RunnableObj runnableObj) {
        super.onPostExecute(runnableObj);

        runnableObj.handler.onSuccess();
    }
}

This is my AsyncTask above.

public void put(final String urlStr, final String requestBody, final HttpResponseHandler httpResponseHandler) {
    RunnableObj obj = new RunnableObj();
    obj.handler = httpResponseHandler;
    obj.request = webb.put(urlStr)
            .header(ServiceConstants.SessionTokenHeader, MyApplication.getSessionToken())
            .ensureSuccess();
    obj.requestBody = requestBody;

    new RunnableTask().execute(obj);
}

This is the method I use to call the Async.

As you can see in the method I use to call the service, I initialise a new instance of RunnableTask each time.

How it performs:

  • The long request will go to the web service and start it's 30 seconds of doing things.

  • 10 seconds later my quick little PUT creates it's object, then the last thing the debugger shows is the break point on the "new RunnableTask().execute(obj);" line and then it just disappears.

  • 20 seconds later the first line of my RunnableTasks doInBackground method will hit and it will perform the PUT.

Please can someone help? Or at least tell me I'm doing something very stupid..


Solution

  • You can execute multiple AsyncTask by using executeOnExecutor

     if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
        new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        new MyAsyncTask().execute();
    }
    

    For more check the AsyncTask documentation