When we need to override Handler's handleMessa

2019-08-17 10:16发布

问题:

I was learning about Looper and Handler and most time I read about it that it use to Communicate with UI thread. But then I saw the code which was child class of Handler with handleMessage(msg : Message) method then I got confused, because we can interact with GUI thread without extending Handler class. As example in kotlin android.

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

So I can easily interact with GUI thread without implementing child class or handleMessage().

Let me explain little more about my quesiton. Sometime 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 code are being used for updating/interacting with GUI thread. but the 1st code is more simple easy and less code to interact with GUI.

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

回答1:

The sendMessage(...) call is used when you want message.obj to be some custom class, to send it to potentially another thread for processing. This is normally done by having message.what be an ID, and knowing the object type for that particular id's message.obj, then casting to that object type. This is used in many places throughout the Android framework, for example check the BluetoothStateMachine and how they handle processMessage(Message msg) in each one of their state classes. Each one of these states is delegated to by Handler.