如何将弱引用传递给活动?

时间:2018-02-16 10:56:23

标签: android kotlin

我试图为android类实现一个主处理程序 如何使用活动的弱引用实例化MyHandler对象?

class MainActivity: AppCompatActivity {
    class MyHandler(var mActivityRef: WeakReference<MainActivity>): Handler(){
        override fun handleMessage(msg: Message?) {
            var activity: MainActivity? = mActivityRef.get()// get actual object from weak reference

            if(activity != null) {
                if (msg?.what == 0) {
                //...some logic
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

我认为最好直接在构造函数中传递Activity实例,然后再做

this.weaActivity = new WeakReference<MyActivity>(activityRef);

MyHandler之外的类不需要知道Activity已保存到Reference。这是仅与MyHandler

相关的实施细节