Ben
Ben

Reputation: 1061

How do I run Async tasks synchronously without post execute chaining?

I have three async tasks, and i'd like to be able to run them synchronously. How can I do that without putting them in onPostExecute of eachother? I'm sorry if this has been covered but I can't seem to get the right key words on google or on here.

new parseZip().execute();
new loadContent().execute();
new playContent().execute();

Any help would be appreciated, or just a link to a thread

Thanks

Upvotes: 4

Views: 5397

Answers (2)

Yash Sampat
Yash Sampat

Reputation: 30611

i'd like to be able to run them synchronously. How can I do that without putting them in onPostExecute of eachother?

Create your own threads for the three separate tasks and synchronize them to execute serially. See here. The author of this slide has also written a book on multithreading in Android.

See also the Specifying the Code to Run on a Thread example.

As an aside, AsyncTasks are run serially by default. If I were you, I'd simply put them in the onPostExecute() of each other. What's wrong with that ?

Upvotes: 3

antonio
antonio

Reputation: 18262

You can query the status of an AsyncTask using getStatus(), to check if a given task has ended and then start the other task, but it would imply to check constantly for the status of wach task and this is not a good idea.

You can also, as you say, start the following task on the onPostExecute of each other, but seeing the names of your tasks I think that you are also using the tasks separately, so it would imply some kind of flag to control whether the tasks should be chained or not.

Maybe the better approach could be to create a new AsyncTask that executes al the work done by each of tour tasks (could need some refactoring to do the work in methods to avoid duplicating your code).

From the documentation:

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.

So, maybe in your case AsyncTaskis not the right tool to do the job and you should think about using plain Threads as @ZygoteInit proposes.

Upvotes: 1

Related Questions