Reputation: 12906
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.
Upvotes: 3
Views: 799
Reputation: 1007658
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
Upvotes: 6
Reputation: 19
A Thread can have one handler and one messageQueue only, a message is some arbitrary data that is handled by the handler whom put on it's messageQueue, the messageQueue loop every message and process them until it has no more message, all data are versatile and executed asap, no need to save it on HDD, it's low level code you dont deal with it often
Upvotes: 1