Should we start async task from within onHandleIntent()
method of IntentService
? I read that onHandleIntent()
runs in worker thread
so will it be safe to start asyncTask
from there??

- 8,660
- 17
- 58
- 91
3 Answers
IntentService
s already are background-processes; there's no need to start an AsyncTask from there. Also, starting an it's a helper class that helps you multithread. Just make sure you don't manipulate AsyncTask
is 'safe' from anywhere;View
s in the doInBackground()
-method of your AsyncTask if you use it in your Activity.
If you need to spawn multiple threads inside your IntentService, just use:
new Thread(Runnable r).start();
See an example at How to run a Runnable thread in Android?
If you need to call some kind of callback, use Handler. For an example, see http://www.vogella.com/articles/AndroidPerformance/article.html#handler
-
4starting an `AsyncTask` is not safe from anywhere: http://stackoverflow.com/questions/4187960/asynctask-and-looper-prepare-error - it is intended to be started from the main thread only, might work if you start it inside `onHandleIntent` since that has a Looper – zapl Nov 21 '12 at 10:28
-
1What if , I don't use asyncTask inside onHandleIntent()? will the code inside it still run in background? – Rookie Nov 21 '12 at 10:51
-
1@zapl, thanks for the comment. Raghav: just call the method you want to call; your UI won't freeze up as the IntentService runs in a different Thread. If for whatever reason you want to spawn multiple threads in your IntentService, just use new Thread(Runnable r).start(); see example at http://stackoverflow.com/questions/1921514/how-to-run-a-runnable-thread-in-android – Reinier Nov 21 '12 at 10:57
-
@Rookie , yes, AFAIK, I use a method to download a file directly inside `onHandleIntent(Intent intent)` method. and it works fine in all the device and varius Operating systmes. – Rumit Patel Dec 19 '19 at 13:48
AsyncTask class is used to provide a mechanism to do achieve multithreading, so your event thread wont get hanged, but as you are using service, you should not use, AsyncTask in the Service, instead you can use, threads, if some long running task is to executed, in the Service.

- 29,001
- 6
- 52
- 53
If you really need to use a AsyncTask inside an IntentService, you can create a method in your AsyncTask that calls de doInBackGround and the onPostExecute. Something like this:
void executeFlowOnBackground(Params params) {
onPostExecute(doInBackground(params));
}
In my case I did this because all App request were made by a class that extended the AsyncTask, and because of the implementation was difficulty to refactor the code.

- 7,036
- 7
- 41
- 64