Can I chain async task sequentially (starting one after the previous asynctask completes)

Solution 1:

I also had some same situation the other day. I had solved it in this way: Pass the reference of your activity to the constructor of async class and execute the do in background function. Now in post execute function call a public method of ur activity from async class to execute the task again... or try this:

            if (asynclass.getStatus() == android.os.AsyncTask.Status.PENDING) {
                asynclass.execute();
            } else if (RF.getStatus() == android.os.AsyncTask.Status.FINISHED) {
                asynclass = new asyncclass();
                asynclass.execute();
            } else {
                Toast.maketoast(this, "Plz wait", 1).show();
            }

Cheers

Solution 2:

so i think(not sure),you need to call second asyncTask on post execution method

protected void onPostExecute(final Void unused) {
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
                     new secTask().execute();
            }}

Solution 3:

Yes, you can. But it is only possible in onProgressUpdate() or onPostExecute(). Try doing it like this:

private class Task1 extends AsyncTask<Void, Void, Void> {
...
...
    protected void onPostExecute(Void unused) { 
        dialog1.dismiss();
        new Task2().execute();
    }

}

Similarly, you'll have to put new Task3().execute(); in the onPostExecute() method of Task2's AsyncTask

Don't call them like this in your main code. If you do, then all of them will run together:

// This is wrong
new Task1().execute();
new Task2().execute();
new Task3().execute();

Reference: AsyncTask

Solution 4:

How about using executOnExecutor method :

public void runTasks() {

        AsyncTask<Void,Void,Void> aTask = myTask();
        AsyncTask<Void,Void,Integer> aTask1 = myTask1();
        AsyncTask<Void,Void,Void> aTask2 = myTask2();

        aTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
        aTask1.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
        aTask2.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);

    }

Solution 5:

Stumbled on this thread looking for a better solution than what I currently use, but it still seems the best...

What I do is pass a runnable in the constructor of each of my async tasks.

Either in the post execute or at the end of the do in the background, I launch my next task, if I have one by executing the runnable.

 if(doOnPostExec != null)
        doOnPostExec.run();

This way I can changeup the order of my asynctasks by the runnables I pass keeping the code flexible, and if I pass no runnable they complete normally. The runnables just contain one line calling the next asynctask.

I just don't like making all those runnables. Was hoping something existed like in vb.net for chaining delegates.