I got slightly confused about the differences between Asynctask
, Thread
, Service
, Loader
in Android.
I know how
It doesn't really matter, what abstraction you use, it boils down to a Thread
. So each of Android's async/parallel classes are using Thread
/Executor
behind the scenes, and have exactly the same potential problems, like locking, that the threads have.
The difference between then lies in its' usage. AsyncTask
for example, defines a handy completion-callback - onPostExecute()
. A CountDownTimer
allows you to control the time and so on.
You can use a plain Thread
of course, but in this case you have to invest more time in catching possible problems yourself.
So, Android provides you with a couple of right tools for right jobs.
I think AsyncTask
is better than Thread
since it provides callback on main thread. Loader
is better than AsyncTask
since it also handles configuration changes for you.
But many peoples says that "Asynctask is outdated", and don't recommend to use them.
I haven't come across someone saying this. But it is the Android team's job to decide when some part of the framework is outdated or deprecated. CursorLoaders
use AsyncTaskLoader
which uses AsyncTask
. AsyncTasks
are an abstraction that prevent the developer from having to implement nasty Thread
state logic. This means that all these classes use in turn useThreads
on the background.
So, is Asynctask really so bad and i should use framework for networking tasks? And what should i use for background (not networking) task?
It is all about knowing when and how to use your tools. You mention CursorLoader
. In that particular case, when you read the docs and play with it a bit, you realize that it purposely integrates smoothly with ContentProviders
. Now, ContentProviders
abstract the underlying data; you can be querying a local SQLite database or a remote server.
Typically, AsyncTasks
are used to retrieve concise pieces of "not-too-large" information (when used to talk with servers). People might say that AsyncTasks
are outdated because there are better(more efficient) ways to interact with servers (see Retrofit).
AsyncTask:
AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask
is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks
should ideally be used for short operations (a few seconds at the most.)
If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent
package such as Executor
, ThreadPoolExecutor
and FutureTask
.
Thread:
Moving numerous or long tasks from the main thread, so that they don’t interfere with smooth rendering and fast responsiveness to user input, is the biggest reason for you to adopt threading in your app.
Use it to separate long running computation from Main Thread ( UI Thread)
Service:
A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface.
A service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
IntentService:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
Loader:
Loader API lets you load data from a content provider or other data source for display in an Activity or Fragment.
Loaders solve these problems and includes other benefits. For example:
Loaders run on separate threads to prevent janky or unresponsive UI.
Loaders simplify thread management by providing callback methods when events occur.
So, is Asynctask really so bad and i should use framework for networking tasks? And what should i use for background (not networking) task?
Use AsyncTask
to handle work items shorter than 5ms in duration. You can use either Thread
Or Service
or IntentService
for the background task.
AysncTasks are not 'outdated' as much as they are incomplete. Among other things async tasks do not bother if their parent activity is currently running or not. For the same reason why you include checks for verify the context to be null or not. Besides, unless you are using your own Thread Pool Executor these tasks execute serially.
Volley tries to fill in those gaps, mainly concerning syncing up with the main thread and thread pooling. It behaves optimal if you wish to do stuff that requires average network requests; like some meta data list and images(picture the youtube app requests and facebook app requests for posts).
Typically few advantages of Volley are as follows
Volley fares badly when it comes to streaming requests/video as mentioned at Google I/O.
I'm not exactly aware of robospice. Ps: If you have time on your hand see https://www.youtube.com/watch?v=yhv8l9F44qo
Here's a further read if you wish to go into other libraries with benchmarks for the same. Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley
Threads: Same as Java threads, use it to do heavy operations but you have to manage it on your own and it can also cause synchronization problems and you can't update UI from it until you are running it on the UI thread.
AsyncTask: A great threading library available in Android for doing background task. It is managed by the android OS itself, you can update the UI from it. It runs in parallel or serially depending upon the version of android. It can be messy sometimes to use it as in the cases of orientation changes and now for making network calls you can use volley which is better than AsyncTask
. AsyncTasks do not bother about their parent activity is running or not and it can be quite tedious to sometimes cancel that. So, I would suggest you if you are using AsyncTask to make rest API calls better use RETROFIT or VOLLEY and if you choose RETROFIT between the two I would recommend you to have a look at PICASSO another awesome library from square for image loading.
Service: For doing long-term background tasks you should use services. You can bound the services to your activity if you need. You can define that they run in the same thread or a different thread and you need to declare it in manifest or you can use IntentService
- a variant of service which runs in its own thread but be careful before using it, don't use it for long running tasks. It's a single time operator. If you are going to use service evaluate the case that which one suits your requirement better a normal Service or IntentService
Loaders: this is same as AsyncTask
in many ways, it is advised to use loaders with the fragments and it solves the orientation problem of the asynctasks.
If you have already moved to kotlin I would suggest you to have a look at Coroutines.These are very lightweight and quite effective for threading and provide you a lot of control over the lifecycle. I hope this helped.