Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask Workflow

I am currently working on an android application that has to handle a network connection using several AsyncTasks.

This is the first task that is establishing the connection and calling a new task which is handling the microphone input.

private class establishConnectionTask extends
        AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            // initialize connection
            initConnection();
            MicrophoneTask micTask = new MicrophoneTask();
            micTask.execute("");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {
        mReadInputTask = new readInputTask();
        mReadInputTask.execute("");
        super.onPostExecute(result);
    }

Everything works fine, the connection is working and I can transfer data. Also the MicrophoneTask is doing it's job.

Here comes the problem:

In the onPostExecute method I am creating a new AsyncTask which should handle all the network input.

This is how the readInputTask looks like:

private class readInputTask extends AsyncTask<String, Integer, String>
{

    @Override
    protected void onPreExecute()
    {
        Log.d("DEBUG", "pre");
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(String... params) {
        // blocking readInput method
          Log.d("DEBUG", "doInBackground");
    }


    @Override
    protected void onPostExecute(String result) {
        Log.d("DEBUG", "post");
        super.onPostExecute(result);
    }
}

The readInputTask somehow gets stuck in the onPreExecute method of the readInputTask. The only output I get is "pre", eventhough I also expect "doInBackground" and "post".

Does anyone see an error or knows a solution for this?

Any help is appreciated!

like image 836
Al0x Avatar asked Dec 11 '25 05:12

Al0x


1 Answers

mReadInputTask.execute("");

When you use AsyncTask#execute(params), the AsyncTasks are executed serially: one after the other. To execute AsyncTasks in parallel, use AsyncTask#executeOnExecutor(...).

From the docs on executeOnExecutor (Executor exec, Params... params):

This method is typically used with THREAD_POOL_EXECUTOR to allow multiple tasks to run in parallel on a pool of threads managed by AsyncTask, however you can also use your own Executor for custom behavior.

like image 66
Vikram Avatar answered Dec 12 '25 17:12

Vikram