kotlin学习笔记

handler这方面最主要的是小心内存泄漏,所以我才用了弱引用,关闭activity关闭时要注销

  private var handler: Handler =  MyHandler(this)

  private class MyHandler(activity: Activity) : Handler() {
        private var mActivity: WeakReference<Activity> = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                101 -> {
                    val activity = mActivity.get()

                    if (activity != null) {
                        activity.tv_now_time.text =
                            (DateFormat.format("HH:MM", System.currentTimeMillis()))
                    }
                }
            }
        }
    }

//使用方式不变
handler.sendMessage(message)


  override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
        EventBus.getDefault().unregister(mContext)
    }

 

引用:https://www.jianshu.com/p/1c817cac2fc3

https://www.jianshu.com/p/f2f186e3dd3e

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐