android Handler内存泄露 kotlin内存泄露处理

这几天使用kotlin写一个项目,用到handler,然后提醒提警告

This Handler class should be static or leaks might occur......

I wrote that debugging code because of a couple of memory leaks I 
found in the Android codebase. Like you said, a Message has a 
reference to the Handler which, when it's inner and non-static, has a 
reference to the outer this (an Activity for instance.) If the Message 
lives in the queue for a long time, which happens fairly easily when 
posting a delayed message for instance, you keep a reference to the 
Activity and "leak" all the views and resources. It gets even worse 
when you obtain a Message and don't post it right away but keep it 
somewhere (for instance in a static structure) for later use. 

百度后才发现是handler内存泄露的问题(原谅小木子是菜鸟)
参考:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1106/1922.html
http://blog.csdn.net/donkor_/article/details/78796518?utm_source=tuicool&utm_medium=referral
android Handler内存泄露 kotlin内存泄露处理_第1张图片

原代码

    private var mHandler1: Handler = object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            if (msg != null) {
                when (msg.what) {
                    CKey.WHAT_TWO -> {
                        verify_tv_again.text = "获取验证码"
                        verify_tv_time.text = ""
                        verify_next.isEnabled = true
                        verify_tv_again.isEnabled = true
                        goToAccountInfoActivity()
                    }
                }
            }
        }
    }

然后按照网站的提示,做了修改:

private class MyHandler(activity: VerifyActivityActivity) : Handler() {
        private val mActivity: WeakReference = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            if (mActivity.get() == null) {
                return
            }
            val activity = mActivity.get()
            when (msg.what) {
                102 -> {
                    activity!!.verify_tv_again.text = "李振华"
                    activity.verify_tv_time.text = ""
                    activity.verify_next.isEnabled = true
                    activity.verify_tv_again.isEnabled = true
//                    activity.goToAccountInfoActivity()
                }
                else -> {
                }
            }
        }
    }

android Handler内存泄露 kotlin内存泄露处理_第2张图片

初始化参数的时候声明一个即可使用(黄色背景即有警告 ,修改后没有了黄色警告)

    var handler12 = MyHandler(this)
    handler12.sendEmptyMessage(102)

效果

android Handler内存泄露 kotlin内存泄露处理_第3张图片

大致讲解:
首先是拿到activity的弱引用 private val mActivity: WeakReference = WeakReference(activity)
然后在需要修改的view之间使用这个引用查找响应的控件做UI修改即可
activity!!.verify_tv_again.text = “李振华”
activity.verify_tv_time.text = “”
activity.verify_next.isEnabled = true
activity.verify_tv_again.isEnabled = true

!!是kotlin非空的意思然后就解除警告,详细讲解参考里面有,就不复制粘贴了,只贴了代码和效果图

你可能感兴趣的:(android碎片,Kotlin)