What is the difference between a Thread and a Handler - android

I'm trying to find out the difference between a thread and a handler. Does creating a new handler create a new thread?. When a new handler is run using post(), is it creating a new thread? Please explain

Threads are generic processing tasks that can do most things, but one thing they cannot do is update the UI.
Handlers on the other hand are bound to threads that allow you to communicate with the UI thread (update the UI).
So for example show a toast or a update a progress bar via a message (Runnable) posted to a handler but you can't if you start this runnable as a thread.
With handler you can also have things like MessageQueuing, scheduling and repeating.
I am yet to encounter a situation where I needed a thread in android.
I mostly use a combination of AsyncTasks and Handlers.
Handlers for the aforementioned tasks.
AsyncTasks for download/ data fetching and polling etc.
You can read the developer article here "Painless Threading" for more threading in android.
Correction:
Each Handler instance is associated with a single thread and that thread's message queue. They are not threads in their own behalf. as described here.

A thread defines a process running. Like you have a main (UI thread) in android. and all other threads run in background.(in parallel).
Handler is completely different, it is like initiating the task defined in a handler..
To clear out your confusion, and perform threading in android you must read :
http://android-developers.blogspot.com/2009/05/painless-threading.html
and i would suggest AsyncTask instead of using Thread in all cases.

Why we use handlers with thread :
When we install an application in android then it create a thread for that application called MAIN UI Thread, All activities run inside that thread , By the android single thread model rule we can not access UI elements (bitmap , textview etc..) directly for another thread defined inside that activity.
So if want to access Main UI Thread elements by another thread then we will use handlers.

Related

What's message queue in Android?

Can someone explain what's the message queue in Android? Is it the list of processes running? I can't find a good source explaining it.
I am asking because I was reading about the method post of the class View.
POST
added in API level 1
boolean post (Runnable action)
Causes the Runnable to be added to the message queue. The runnable
will be run on the user interface thread.
Thank you in advance.
In simple terms a MessageQueue is a list of tasks (Messages, runnables) that will be executed in a certain thread. The Android system has a very known main thread (the UI one). The method you just saw simply adds a runnable to the list of processes that will be executed in the UI thread. Alongside with Looper and Handler, MessageQueues are part of the bulding blocks of threading in Android and they are used virtually everywhere in the system.
When would you use this method?
Whenever you want to update some UI element (View element) from another thread. Maybe you're doing some heavy lifting in another thread and want to update the UI element, you can't update the UI elements in others threads but the UI thread so you post changes to be executed in the UI thread.
You can learn more about MessageQueues here and here.
to Understand MessageQueue, you need understand executing model of android app;
Just like Javascript, Cocoa in iOS, to avoid cocurrency access racing, many App related framework adapts a single thread model.
that means there is a main thread, you put your work that need be done into the queue(MessageQueue) dedicated to this thread, there is a worker(Looper) that will reteive your work from the queue, run them one by one;
this model avoid cocurrency collision in the app;
when you need do a longtime job , you should put the work into the main thread queue, when it's to do your work in the message , you create a new thread to do this longtime job, after job is done , you put a new message into the main thread message queue from your new thread;
this picture will help you understand the running model

Looper or while in a thread?

I'm trying to understand the Looper...
This time i'm getting a little bit confused, because I've only used (until now) the while(true) condition to maintain the thread in an infinite loop.
I just want to know if it is better to use the Looper or the while(true) condition.
I've searched a possible answer to my question in internet and I was quite disappointed in finding codes that use Looper and while(true) together.
Probably I didn't get the point of using the Looper but, you know, we are here to learn... isn't it?
Looper is a mechanism that keeps thread open to process Messages that are sent to it via Handler. In that sense, they are similar to while(true) in that the Thread stays open forever (or in this case until you explicitly tell it to close). However, unlike while(true), you can send the Messages to it from another thread. Every time you create a Handler, it binds itself to the Looper thread that it was created in. Then, every time you post a message to that Handler, it processes that message on the thread in which it was created.
The most common, well-known Looper thread in Android is the main UI thread. This thread is always running. It runs code that are posted to it. Most commonly drawing operations, but if you take a view and call View#post, it will run the code in the next draw cycle. This is because all View objects have a Handler that was built on the main UI Looper thread.
The UI Looper can actually be referenced to Looper.getMainLooper() method, and you can create a Handler that posts messages to this thread like so: new Handler(Looper.getMainLooper());.
Though if you need, you could create your own Looper thread that acts as a parallel thread to the UI thread. You can't do drawing operations on it, but you could use it as a worker thread for other operations. That way you don't have the overhead of creating a new thread every time you need to do something intensive.
I just want to know if it is better to use the Looper or the while(true) condition.
I'd say, as a general rule, unless you need some very specific low-level control, use the API that are provided by the framework, whichever the framework is.
They usually take care of many aspects that would otherwise have you implement them yourself, such as messaging, task deletion, and so on...
I guess that with the while (true) loop you are trying to achieve some regular task repetition.
In this particular case, yes, use a Handler with its own Looper, so the UI Thread is not blocked, and post your Runnable instances regularly with postDelay(Runnable, long).
#DeeV 's answer already gives you a good understanding about the mentioned components, but you sure will find out everything you need in Android documentation.

Executing a Thread in Asynctask and its complications

I was wondering is it ok to execute a Thread inside the doInBackground method of Asynctask. Should I avoid using this kind of structure on my codes? And if yes, why should I avoid it? Would this cause any ineffectiveness in my apps?
In principle, there's no problem with starting a thread in the doInBackground() of an AsyncTask, but sometimes you see this done not because it's the right thing to do, but because of a misunderstanding about how AsyncTask works.
The point is that doInBackground() will automatically get executed on a background (non-GUI) thread, without you needing to create a thread for it yourself. That, in fact, is the whole point of an AsyncTask. So if you have a simple, linear task that you want executed in the background, you do it with an AsyncTask, and you don't need to do any manual thread creation.
Where you might want to start a new thread in an AsyncTask is if you want your background task to use multiple threads to complete. Suppose that you were writing an app to check the online status of various servers, and display something about their status on the screen. You'd use an AsyncTask to do the network access in the background; but if you did it in a naive way, you'd end up with the servers being pinged one by one, which would be rather slow (especially if one was down, and you needed to wait for a timeout). The better option would be to make sure that each server was dealt with on its own background thread. You'd then have a few options, each of which would be defensible:
Have a separate AsyncTask for each server.
Create a thread for each server inside the doInBackground() of your single AsyncTask, and then make sure that doInBackground() doesn't complete until all the individual threads have completed (use Thread.join()).
Use a ThreadPool / some kind of ExecutorService / a fork/join structure inside your single AsyncTask, to manage the threads for you.
I would say that with modern libraries there is rarely a need for manual thread creation. Library functions will manage all of this for you, and take some of the tedium out of it, and make it less error-prone. The third option above is functionally equivalent to the second, but just uses more of the high-level machinery that you've been given, rather than going DIY with your thread creation.
I'm not saying that threads should never be created manually, but whenever you're tempted to create one, it's well worth asking whether there's a high-level option that will do it for you more easily and more safely.
is it ok to execute a Thread inside the doInBackground method of
Asynctask.
yes it is but it really depends on your application and your usage. for example in a multithread server-client app you must create for each incoming clients one thread and also you must listen on another thread. so creating thread inside another is ok. and you can use asynctask for listening to your clients.
Should I avoid using this kind of structure on my codes? And if yes,
why should I avoid it?
If you design it carefully you do not need to avoid, for example make sure that on rotation you do not create another asynctask because for example if your user rotates 5 times you create 5 asynctasks and in each of them you create a thread that means you will get 10 threads, soon you will get memory leak.
Would this cause any ineffectiveness in my apps? Can you explain
these questions please.
I answered it above, I think better idea is using Thread Pool to minimize number of creating your threads or wraping your asynctask in a UI less fragment so you are sure you have one asynctask regardless of whats going to happen.
In any higher programming language, there is concept of multi-tasking. Basically the user needs to run some portion of code without user interaction. A thread is generally developed for that. But in Android, multi-tasking can be done by any of the three methods Thread and AsyncTask.
Thread
A thread is a concurrent unit of execution. It has its own call stack. There are two methods to implement threads in applications.
One is providing a new class that extends Thread and overriding its run() method.
The other is providing a new Thread instance with a Runnable object during its creation.
A thread can be executed by calling its "start" method. You can set the "Priority" of a thread by calling its "setPriority(int)" method.
A thread can be used if you have no affect in the UI part. For example, you are calling some web service or download some data, and after download, you are displaying it to your screen. Then you need to use a Handler with a Thread and this will make your application complicated to handle all the responses from Threads.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each thread has each message queue. (Like a To do List), and the thread will take each message and process it until the message queue is empty. So, when the Handler communicates, it just gives a message to the caller thread and it will wait to process.
If you use Java threads then you need 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
AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
1. onPreExecute()
Invoked on the UI thread before the task is executed
2. doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute() finishes executing.
3. onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
4. onPostExecute(Result)
Invoked on the UI thread after the background computation finishes.
And there are lot of good resources over internet which may help you:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html http://www.mergeconflict.net/2012/05/java-threads-vs-android-asynctask-which.html
I would say there is no problem in doing that if you need something to run concurrently beside the AsyncTask.
One issue could be one of readability (using 2 different ways for concurrency), but I really can't see the harm in that - especially if one of the tasks needs to show it's result in the UI and the other one doesn't.

Difference between AsyncTask and Thread/Runnable

I have question which puzzles me.
Imagine I wanna do something in another thread, like fetching GPS/Location stuff, which as recommended in the SDK documents, must use a background thread.
So here is the question: What's the difference between
Creating a Thread in background via AsyncTask AND
Creating Thread thread1 = new Thread(new Runnable() ... and implementing run()?
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.
Key differences:
AsyncTask is an asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. It can't be done with normal thread unless you use Handler on UI Thread and post a message OR directly change attribute of an object by implementing proper synchronization.
As recommended by developer guide regarding Thread performance,
There are a few important performance aspects to keep in mind. First, by default, an app pushes all of the AsyncTask objects it creates into a single thread. Therefore, they execute in serial fashion, and—as with the main thread—an especially long work packet can block the queue. For this reason, we suggest that you only use AsyncTask to handle work items shorter than 5ms in duration..
But normal Thread can be used for long running tasks.
Plain java Threads are not much useful for Android unlike HandlerThread, which has been provided by Android framework.
Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.
Refer to below post to know more details:
Handler vs AsyncTask vs Thread
Also take in count that starting on Android v4.04, you can't have more than one AsyncTasks at a time, unless you lose compatibility with lower versions. Be aware!
AsyncTask deprecated with api level 30. Using thread/runnable is convenient
One obvious drawback for AsyncTask class is that after Android 3.0 asynctasks are executed according to the sequence of the start time. that is tasks are executed one by one, unless you execute the task by calling 'executeOnExecutor(Executors.newCachedThreadPool())'. this method would create your own thread pool.
Better to use the new Job Scheduler in the support library.

What is the difference between AsyncTask and Handlers and which one would be better to use in Listview?

I'm using multiple lists embedded one inside another. This obviously slows down the App, thus I thought of using multi-threading. Treating separate lists as threads, and then the data loaded inside them as separate threads to make it faster.
Is this a better way to do it? Can I've certain examples based on it? Or even links?
The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.
AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
It is better to use an async task to load a listview so you dont block the main UI
Your question title does not match the question body, you'll get better responses if you change them to relate better.
See the following question for an explaination of the differences: How to know when to use an async task or Handler
That said, in your case, you want to parralelize the population of the listboxes as opposed to the handling of messages, so AsyncTask makes most sense.
Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler can be created from any thread and it runs on the thread which created it.
It handles and schedules messages and runnables sent from background to the thread which created it
.
We should consider using handler it we want to post delayed messages or send messages to the MessageQueue in a specific order.
AsyncTask is always Triggered or created from main thread.
Its methods onPreExecute(),onPostExecute(),onProgressUpdate() runs on main thread(or UI thread) and doInBackground() runs on worker thread(or background thread).AsyncTask enables proper and easy use of the UI thread.
This class allows to perform background operations and publish results on the UI thread .
We should consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.

Categories

Resources