【问题标题】:How to use Handler and handleMessage in Kotlin?如何在 Kotlin 中使用 Handler 和 handleMessage?
【发布时间】:2018-08-26 10:10:43
【问题描述】:

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 上给出了编译时错误

【问题讨论】:

    标签: android kotlin android-handler


    【解决方案1】:

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

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

    private val mHandler = object : Handler() {
    
        override fun handleMessage(msg: Message?) {
            // Your logic code here.
        }
    }
    

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

    这个 Handler 类应该是静态的,否则可能会发生泄漏。

    由于这个 Handler 被声明为一个内部类,它可能会阻止 外部类被垃圾收集。如果处理程序正在使用 Looper 或 MessageQueue 用于主线程以外的线程,然后 没有问题。

    如果Handler使用的是主线程的Looper或者MessageQueue, 您需要修复您的 Handler 声明,如下所示: Handler 作为静态类;在外部类中,实例化一个 对外部类的弱引用并将此对象传递给您的处理程序 当您实例化处理程序时;对成员的所有引用 使用 Wea​​kReference 对象的外部类。

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

    【讨论】:

    • 这给出了 HandlerLeak lint 警告
    • @BeniBela 感谢您的信息,请查看我的更新答案。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      就我而言:

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

      【讨论】:

        猜你喜欢
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多