Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - What is a Handler Message?

I'm talking about this class.

The main documentation states:

Defines a message containing a description and arbitrary data object that can be sent to a Handler. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.

  • So I would assume that it is some kind of communication between different threads, maybe a Bundle?

  • There are also a few snippets in the main documentation. But I can't see how are they built and what is their structure.

  • Why to use them instead of using SharedPreferences or maybe a Singleton class? Testing?


I would love to see a little and compact example on when and how to use them.

like image 438
Evin1_ Avatar asked Apr 30 '26 06:04

Evin1_


1 Answers

So I would assume that it is some kind of communication between different threads

You can attach a Handler to the main application thread (a.k.a., UI thread), and you can create separate HandlerThread instances for other threads with associated Handler instances.

One thread can send a Message, via a Handler, where the Handler will process the Message on its own thread, in the handleMessage() method. For example, a regular background Thread could package the results of its work (e.g., downloaded data) into a Message, and give that to a Handler attached to the main application thread. That Handler will get the Message in handleMessage(), called on the main application thread, and can then update the UI safely using the data from the background thread.

This is a very low-level means of inter-thread communication in Android. More often, you are better served using something a bit higher-order, like an event bus.

Why to use them instead of using SharedPreferences

SharedPreferences are for data storage, not inter-thread communication.

or maybe a Singleton class?

While a singleton can provide a central point of data, on its own, it does not provide any sort of inter-thread communication.

I would love to see a little and compact example on when and how to use them.

For 99% of Android developers, the answer is: don't use them. Use something that is built on top of Handler and Message, such as:

  • AsyncTask
  • LocalBroadcastManager
  • Square's Otto
  • greenrobot's EventBus
  • etc.
like image 123
CommonsWare Avatar answered May 01 '26 19:05

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!