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?
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.
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With