当我们需要重写Handler的handleMessage()方法时 [英] When we need to override Handler's handleMessage() method

查看:981
本文介绍了当我们需要重写Handler的handleMessage()方法时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习关于Looper和Handler的知识,并且大多数时候我读到它用于与UI线程通信的知识.但是后来我看到了用handleMessage(msg : Message)方法作为Handler子类的代码,然后感到困惑,因为我们可以与GUI线程进行交互而无需扩展Handler类. 以kotlin android为例.

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
});

因此,我可以轻松实现与GUI线程的交互,而无需实现子类或handleMessage().

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..
});

因此在上面的示例中,两个代码都用于更新/与GUI线程交互.但是第一个代码更简单易用,与GUI交互的代码更少.

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.

那么handleMessage()方法的真正目的是什么,什么时候应该实现呢?

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

推荐答案

当您希望message.obj为某个自定义类时,将使用sendMessage(...)调用,以将其发送到可能的另一个线程进行处理.通常,通过使message.what为ID并知道该特定ID的message.obj的对象类型,然后强制转换为该对象类型,来完成此操作.这在整个Android框架中的许多地方都使用过,例如,检查

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.

这篇关于当我们需要重写Handler的handleMessage()方法时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆