I was developping an application and I ran into a problem. I was trying to run an asynchronous task from a service and it didn't work. It says that the code is unreachable. Now I knwo that both run in Background, but I really want one service to control several asyncronous tasks. how can I do that? Do I have to use threads? I've read this post and I really want to use the asyncronous task: Difference between Service, Async Task & Thread?
Also, is it possible to execute an asynchronous task from another one?
Thank you
AsyncTask
always works on main/UI thread. And if yourService
is running under a different process then it is not associated to main thread, that's why you cant useAsyncTask
inService
.In your case, you are encouraged to use
HandlerThread
,Looper
andHandler
to perform heavy lifting on separate thread.Read this article.
There's a few options. If you need communication between your task and say, an activity, AsyncTask would be your best best, IMO. If you just need to "fire and forget", IntentService can be of help.
Remember, a service still runs on the main thread. If you need to do anything that requires some processing or lookup such as network download/upload or SQL queries, you should move that to a new thread using on of the aforementioned classes.
you can use
HandlerThread
in your service for doing background work like: