Kotlin中如何使用Handler和handleMessage?

How to use Handler and handleMessage in Kotlin?

Java代码:

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
       // code here
    }
};

如何将此 java 代码转换为 Kotlin?

我试过这个:

private val mHandler = object : Handler() {
    fun handleMessage(msg: Message) {
       // code here
    }
}

但这似乎是不正确的,并且在 object

上给出了编译时错误

问题: 覆盖 Handler class 的 handleMessage() 方法的语法不正确。

解决方法:在要覆盖的函数前添加override关键字。

private val mHandler = object : Handler() {

    override fun handleMessage(msg: Message?) {
        // Your logic code here.
    }
}

更新: 正如@BeniBela 的评论,当使用上面的代码时,会显示一个 lint 警告

This Handler class should be static or leaks might occur.

Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue.

If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.

class OuterClass {

    // In the outer class, instantiate a WeakReference to the outer class.
    private val outerClass = WeakReference<OuterClass>(this)

    // Pass the WeakReference object to the outer class to your Handler
    // when you instantiate the Handler
    private val mMyHandler = MyHandler(outerClass)

    private var outerVariable: String = "OuterClass"

    private fun outerMethod() {

    }

    // Declare the Handler as a static class.
    class MyHandler(private val outerClass: WeakReference<OuterClass>) : Handler() {

        override fun handleMessage(msg: Message?) {
            // Your logic code here.
            // ...

            // Make all references to members of the outer class 
            // using the WeakReference object.
            outerClass.get()?.outerVariable
            outerClass.get()?.outerMethod()
        }
    }
}

就我而言:

@SuppressLint("HandlerLeak")
    private inner class MessageHandler(private val mContext: Context) : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {

            }
        }
    }

通过将 looper 传递给处理程序,您可能会更容易一些(没有 WeakReference):

val handler = object:  Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            doStuff()
        }
    }