Difference between Service, Async Task & Thread?
Probably you already read the documentation description about them, I won't repeat them, instead I will try to give answer with my own words, hope they will help you.
Service is like an Activity but has no user interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.
A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.
An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are three methods that run on UI thread, which is good to update UI components.
I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.
Real difference between AsyncTask and Thread
Please read this blog
http://crazyaboutandroid.blogspot.in/2011/12/difference-between-android.html
and Details are:
Difference between Android Service,Thread,IntentService and AsyncTask
When to use ?
Service
Task with no UI, but shouldn't be too long. Use threads within service for long tasks.
Thread
- Long task in general.
- For tasks in parallel use Multiple threads (traditional mechanisms)
AsyncTask
- Small task having to communicate with main thread.
- For tasks in parallel use multiple instances OR Executor
Asynctask vs Thread vs Services vs Loader
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
- It keeps the worker thread informed about the activity(Main thread)
- Easier resource prioritization you could provide priority to your download requests.
A typical scenario would involve you giving priority to text over image. - Effective request cache and memory management.
- Extensible
- It provides you an option to discard your request in-case your activity was shutdown or restarted.
- Simpler patterns for data retrieval as opposed to AsyncTasks.
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
Android: AsyncTask vs Service
In some cases it is possible to accomplish the same task with either an AsyncTask
or a Service
however usually one is better suited to a task than the other.
AsyncTask
s are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.
Service
s are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask
that will run once, return the data, and be done.
If you need to be continually doing something in the background, though, a Service
is your best bet. Examples of this include playing music, continually checking for new data, etc.
Also, as Sherif already said, services do not necessarily run off of the UI thread.
For the most part, Service
s are for when you want to run code even when your application's Activity
isn't open. AsyncTask
s are designed to make executing code off of the UI thread incredibly simple.
Asynctask vs Thread in android
For long-running or CPU-intensive tasks, there are basically two ways to do this: Java threads, and Android's native AsyncTask.
Neither one is necessarily better than the other, but knowing when to use each call is essential to leveraging the system's performance to your benefit.
Use AsyncTask for:
- Simple network operations which do not require downloading a lot of data
- Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
- Network operations which involve moderate to large amounts of data (either uploading or downloading)
- High-CPU tasks which need to be run in the background
- Any task where you want to control the CPU usage relative to the GUI thread
And there are lot of good resources over internet which may help you:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
Handler vs AsyncTask vs Thread
As the Tutorial on Android background processing with Handlers, AsyncTask and Loaders on the Vogella site puts it:
The Handler
class can be used to register to a thread and provides a simple channel to send data to this thread.
The AsyncTask
class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.
And a Thread
is basically the core element of multithreading which a developer can use with the following disadvantage:
If you use Java threads you have to handle the following requirements
in your own code:
- Synchronization with the main thread if you post back results to the user interface
- No default for canceling the thread
- No default thread pooling
- No default for handling configuration changes in Android
And regarding the AsyncTask
, as the Android Developer's Reference puts it:
AsyncTask
enables proper and easy use of the UI thread. This class
allows 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 aroundThread
andHandler
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.
Update May 2015: I found an excellent series of lectures covering this topic.
This is the Google Search: Douglas Schmidt lecture android concurrency and synchronisation
This is the video of the first lecture on YouTube
All this is part of the CS 282 (2013): Systems Programming for Android from the Vanderbilt University. Here's the YouTube Playlist
Douglas Schmidt seems to be an excellent lecturer
Important: If you are at a point where you are considering to use AsyncTask
to solve your threading issues, you should first check out ReactiveX/RxAndroid
for a possibly more appropriate programming pattern. A very good resource for getting an overview is Learning RxJava 2 for Android by example.
Android Thread difference between AsyncTask, Executor and Service
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.)
Read docs
Executor is just an object that executes submitted Runnable tasks.
Read docs
Service does not relate to multi-threading at all. A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.
Read docs
Difference between AsyncTask and Thread/Runnable
AsyncTask is a convenience class for doing some work on a new thread and use the results on the thread from which it got called (usually the UI thread) when finished. It's just a wrapper which uses a couple of runnables but handles all the intricacies of creating the thread and handling messaging between the threads.
AsyncTask enables proper and easy use of the UI thread. This class allows 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 pacakge such as Executor, ThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
The Runnable interface is at the core of Java threading. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
Also if I quote from this blog:
if you need SIMPLE coding use AsyncTask and if you need SPEED use traditional java Thread.
Android - Difference between Thread and AsyncTask?
When you use a Thread
, you have to update the result on the main thread using the runOnUiThread()
method, while an AsyncTask
has the onPostExecute()
method which automatically executes on the main thread after doInBackground()
returns.
While there is no significant difference between these two in terms of "which is more beneficial", I think that the AsyncTask
abstraction was devised so that a programmer doesn't have to synchronize the UI & worker threads. When using a Thread
, it may not always be as simple as calling runOnUiThread()
; it can get very tricky very fast. So if I were you, I'd stick to using AsyncTask
and keep Thread
for more specialized situations.
what is difference between kotlin coroutine and asyncTask class and multiThread
AsyncTask
was the first hand solution proposed by Google in Android SDK in order to process work in the background, while keeping the main thread free from many complex operations. In fact, AsyncTask
let you to do complex processing in an asynchronous manner. Compared to classical Java Thread
, the AsyncTask
was somehow specialized, providing UI wrappers around threads in order to allow a more enjoyable experience as a developer, coding in an async way. The AsyncTask
class was deprecated in the meantime and the recommended way to solve things is by using coroutines.
Coroutines are not a new concept introducer by Kotlin, in fact this concept exists in a lot of programming languages (Go has Goroutines and Java will provide something called Fibers). The main advantage of using coroutines is the simplicity of code, the only thing that differentiate a sync task/function in face of an async task/function is the usage of suspend
keyword put in front of the function.
For example, the following function is executed in a synchronous way:
fun doSomething() = println("Print something")
while the following one is executed on a asynchronous way, due to the usage of suspend
keyword:
suspend fun doSomething() = println("Print something")
When a suspend
function is reached, the program will not block there, and will go further in running the rest of the code, but will receive a Continuation
which will return the value computed by the suspended function when this one will be available.
Related Topics
Bitmapfactory Oom Driving Me Nuts
Finish an Activity from Another Activity
Android:How to Set Onclick Event for Button in List Item of Listview
How to Disable Action Bar Permanently
How to Get the Touch Position in Android
Android Activity Over Default Lock Screen
Why Extend the Android Application Class
Pass a String from One Activity to Another Activity in Android
How to Kill an Application with All Its Activities
Passing Arraylist of Objects Between Activities
Get the Current Language in Device
Enabling Proguard in Eclipse for Android
Best Practice: Asynctask During Orientation Change
Latest Update on Enabling and Disabling Mobile Data Programmatically
How to Increase Storage for Android Emulator? (Install_Failed_Insufficient_Storage)
Custom Filtering in Android Using Arrayadapter
How to Make an Android App Return to the Last Open Activity When Relaunched