Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler vs Thread

I would like to know, once for all. I've read in many places. When I want do some 'long time operations' I should use a Handler.

But I don't get why? All my 'long-time-operations' I surround with a regular threads, and it works fine.

Why would I use Handler for this?

The only time I had to use Handler was, when I had to schedule some task(postDelayed)

Is there any main idea I miss about handlers(When I should really use it)? Or maybe there isn't really difference?

like image 803
rayman Avatar asked Jun 23 '10 13:06

rayman


People also ask

What is the difference between handler and thread?

The main difference between Handler and Thread is that a handler is a function or a method that is capable of performing a specific task while a thread is a small, lightweight execution unit within a process.

What is the difference between handler vs AsyncTask vs thread?

AsyncTask are similar, in fact, they make use of Handler , but doesn't run in the UI thread, so it's good for fetching data, for instance fetching web services. Later you can interact with the UI. Thread however can't interact with the UI, provide more "basic" threading and you miss all the abstractions of AsyncTask .

What is handler of a thread in Java?

Thread handlers are implemented in the main thread of an application and are primarily used to make updates to the user interface in response to messages sent by other threads running within the application's process.

What is thread and handler in Android?

Option 3: Using HandlerA Handler is a component that can be attached to a thread and then made to perform some action on that thread via simple messages or Runnable tasks. It works in conjunction with another component, Looper , which is in charge of message processing in a particular thread.


2 Answers

A Handler lets you communicate back with the UI thread from your background thread. This is because UI operations are forbidden from within background threads. Note that starting at version 1.5, the AsyncTask class makes it much easier to do so.

like image 148
JRL Avatar answered Sep 25 '22 01:09

JRL


It can't just be about getting you back to the UI thread since runOnUiThread(Runnable) does that very nicely. I suspect this is more about making it easier for Android to manage threads and other resources that shouldn't live outside of an Activity's context, and that the "Activity has leaked..." exceptions tell you when that's happened.

like image 32
Melinda Green Avatar answered Sep 26 '22 01:09

Melinda Green