Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

android - How to use Handler and handleMessage in Kotlin?

Java code:

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

How to convert this java code to Kotlin?

I tried this:

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

But this is seems to be incorrect and gives a compile time error on object

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem: The syntax to override handleMessage() method of the Handler class is incorrect.

Solution: Add override keyword before the function that you want to override.

private val mHandler = object : Handler() {

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

Update: As @BeniBela's comment, when using above code, a lint warning will be displayed

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...