4

Is it a must that we have to initiate and execute asyctask from UI thread.Is it correct if i use asynctask for a webservice access(long running) from a non ui thread. sorry if my query is wrong.

In my app i have to run around 10 webservices and have to show the result on ui .i am confused which approach will be good asynctask,intentservice or creating thread for each webservice call and making it to run parallel.

Niju Mt
  • 159
  • 3
  • 10

3 Answers3

2

There are a few threading rules that must be followed for AsyncTask to work properly:

  1. The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.

  2. The task instance must be created on the UI thread.

  3. execute(Params...) must be invoked on the UI thread.

  4. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.

  5. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

    Further Details

In my personal opinion, I would suggest using AsyncTask as it is highly optimized for running background tasks and exploit benefits like multicore processor.

Rahul Verma
  • 2,140
  • 3
  • 21
  • 31
  • 1
    this is false, an `IntentService` does not need an AsyncTask, it already runs in the background `IntentService is a base class for Services that handle ASYNCHRONUS requests (expressed as Intents) on demand.` http://developer.android.com/reference/android/app/IntentService.html – tyczj Jan 23 '13 at 19:13
  • @tyczj What you've said is true, but so is Rahul's answer, although it *might* not answer the OP. He didn't say anything about IntentService using an AsyncTask. I suspect that the OP needs IntentService though. – Simon Jan 23 '13 at 20:50
  • @Simon Yes I was only talking about the intentservice part being wrong – tyczj Jan 23 '13 at 21:09
0

Yes, asynctask needs to be run from the UI thread.

I'd suggest to use multiple threads/runnables. You'll also need to implement a handler in your main activity class to listen to the responses from the threads.

paulczak
  • 96
  • 6
0

You can go with either thread or asynctask. AsyncTask provide you methods to manage Ui changes methods before starting background task and after finishing backgroung task or getting its progress.

It depends on your architecture requirement.

DcodeChef
  • 1,550
  • 13
  • 17