How do you implement two-way communication between two threads with Handlers in Android?
I have a Service A that spawns thread B. It's fairly easy to communicate from B to A, it's just to pass a Handler to the constructor of B, but how to do it from A to B? B does not have any Looper assigned to it automatically.
Has anyone got the answer?
The most common thread communication use case in Android is between the UI thread and worker threads. Hence, the Android platform defines its own message passing mechanism for communication between threads. The UI thread can offload long tasks by sending data messages to be processed on background threads.
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.
A Handler allows communicating back with UI thread from other background thread . This is useful in android as android doesn't allow other threads to communicate directly with UI thread. A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.
Here is good post explaining threads and communication using handlers. Also, the same blog has a number of posts regarding various thread constructs in Android
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