Handler VS Asynctask VS Thread

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 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.

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.

  1. The reason why AsyncTask is recommended for only short tasks (around 5 seconds) is there is no method to cancel a running AsyncTask. There exists a method called AsyncTask.cancel(true) which invokes onCancelled(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 with Thread.interrupt().
  2. There shouldn't be any problem running an AsyncTask within a Service provided that you are aware of the cancellation limitation of AsyncTask and the possibility of memory leak can be created by AsyncTask. Note that, there is obviously no need to use an AsyncTask in an IntentService which is already running in a worker thread.
  3. 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 to RxJava. You can perhaps find one of the specific questions here. There are also a whole bunch of discussions about handling leaking/screen rotation with RxJava 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, AsyncTasks 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:

  1. Simple network operations which do not require downloading a lot of data
  2. Disk-bound tasks that might take more than a few milliseconds

Use Java threads for:

  1. Network operations which involve moderate to large amounts of data (either uploading or downloading)
  2. High-CPU tasks which need to be run in the background
  3. 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



Leave a reply



Submit