When do we need to override the Handler handleMessage () method

I learned about Looper and Handler, and in most cases I read about it, which it uses to communicate with the user interface thread. But then I saw code that was a child of the Handler class with the handleMessage(msg : Message) method, then I got confused because we can interact with the GUI thread without extending the Handler class. As an example in kotlin android.

 val handler = Handler(); handler.post({ // update GUI here }); 

Therefore, I can easily interact with the GUI thread without implementing a child class or handleMessage() .

Let me explain a little more about my quesiton. Sometimes I see this example.

 class HandlerSub : Handler(){ override fun handleMessage(msg : Message){ // update GUI here. } } val handler = HandlerSub(); handler.send({ // send something.. }); 

So, in the above example, both codes are used to update / interact with the GUI thread. but the first code is simpler and lighter code for interacting with the graphical interface.

Then what is the real purpose of the handleMessage() method and when should we implement it?

-2
android kotlin
Nov 16 '17 at 18:03
source share
1 answer

The sendMessage (...) call is used when you want message.obj to be some kind of special class to send it to a potentially different thread for processing. This is usually done using message.What is the identifier and knowledge of the type of the object for this particular message id.obj, and then for that type of object. This is used in many places throughout the Android platform, for example, check the BluetoothStateMachine and how they handle processMessage(Message msg) in each of their state classes. Each of these states is delegated by the handler.

0
Nov 16 '17 at 19:31 on
source share



All Articles