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.
Handler vs AsyncTask
IMO, AsyncTask was written to provide a convenient, easy-to-use way to achieve background processing in Android apps, without worrying too much about the low-level details(threads, message loops etc). It provides callback methods that help to schedule tasks and also to easily update the UI whenever required.
However, it is important to note that when using AsyncTask, a developer is submitting to its limitations, which resulted because of the design decisions that the author of the class took. For e.g. I recently found out that there is a limit to the number of jobs that can be scheduled using AsyncTasks.
Handler is more transparent of the two and probably gives you more freedom; so if you want more control on things you would choose Handler otherwise AsynTask will work just fine.
Android AsyncTask vs Thread + Handler vs rxjava
Since no one's replying. I'm answering my own questions then.
- The reason why
AsyncTask
is recommended for only short tasks (around 5 seconds) is there is no method to cancel a runningAsyncTask
. There exists a method calledAsyncTask.cancel(true)
which invokesonCancelled(Result result)
. However, according to the docs, this method "runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished." (https://developer.android.com/reference/android/os/AsyncTask.html). On the other hand,Thread
can be stopped withThread.interrupt()
. - There shouldn't be any problem running an
AsyncTask
within aService
provided that you are aware of the cancellation limitation ofAsyncTask
and the possibility of memory leak can be created byAsyncTask
. Note that, there is obviously no need to use anAsyncTask
in anIntentService
which is already running in a worker thread. - This is a very experience-based question. I guess there would be no complete answer. What we can do is to understand Rx and being aware of the its limitations to determine where suitable to use it. In my development work, I use
RxJava
all the time without having any issue. Note that the same memory leaking issue is also applied toRxJava
. You can perhaps find one of the specific questions here. There are also a whole bunch of discussions about handling leaking/screen rotation withRxJava
that can be easily found by Googling.
Thread vs Handler vs Async task for sockets in android?
You can use both a Thread
or an AsyncTask
, just chose one of the two based on your needs (if you provide more details about the task you need to perform I might be able to help you more specifically).
The Handler
class is not meant to be used to run asynchronous tasks (like Thread
and AsyncTask
), an Handler
instance is used to allow communication between two threads, for instance, if you decide to use the Thread
over the AsyncTask
, an Handler
class will help you with data exchange between your UIThread and the Thread that handles the socket.
Now, AsyncTask
s are perfect for working as a Client. If what you need is opening a Server socket you should forget about those and try to have a look at the Service
and choose between Service
and Thread
.
Why?
Because AsyncTask
are meant to perform a specific job in a relatively little time. To open a server, which will need to stay opened for (possibly) a long time that's not the class you need.
I'd take a look at the Service
because it provides some useful methods to interact with the Android application lifecycle.
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
Use Threads vs. Handlers vs. AsyncTask in an Android App sending UDP datagrams
You have a real mix of technologies there, and they don't fill the same slot. So no wonder you're confused.
Runnable- this is just a function that can be saved and called whenever. It may be of use in writing a solution, but it provides no asynchronous ability whatsoever by itself.
Handler- a handler is a message queue that runs on a particular thread. That thread must have set up a Looper. If you want to post messages from one thread to another, this can be the message passing mechanism, but it doesn't provide asynchronous ability in and of itself.
Thread- is an actual thread. Its a function that can run in parallel to your main thread. This is probably what you actually want.
AsyncTask- Basically a thread that runs some code on the main thread before and after running some code. It removes the burden of doing that message passing yourself. This is a simplification, but its a good enough explanation. AsyncTasks should only be used for 1 off quick operations. While you'll see examples of it being used for HTTP transfers, it really shouldn't be.
Basically what you want is a Thread for the asynchronous part, with a method to pass messages to that thread. A Thread with its own Looper and a Handler for that looper would work well. Then the Thread can just read messages off that Handler, and the sensor reading code can post it to the handler. The Thread itself will run in the background when it has work to do, until you interrupt it to end the Thread at shutdown time.
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.
Related Topics
Run/Install/Debug Android Applications Over Wi-Fi
How to Check Programmatically If an Application Is Installed or Not in Android
How to Get the Web Page Contents from a Webview
Android Fragment No View Found For Id
Getactivity() Returns Null in Fragment Function
Android Take Screenshot of Surface View Shows Black Screen
Difference Between a View'S Padding and Margin
Android and Xmpp: Currently Available Solutions
Do Fragments Really Need an Empty Constructor
How to Increase Heap Size of an Android Application
Automatically Accept All Sdk Licences
How to Create a Custom-Shaped Bitmap Marker With Android Map API V2
Synchronise Scrollview Scroll Positions - Android
Android Sqlite Database: Slow Insertion
Android How to Use Mediascannerconnection Scanfile