我试图为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
}
}
}
}
}
答案 0 :(得分:2)
我认为最好直接在构造函数中传递Activity
实例,然后再做
this.weaActivity = new WeakReference<MyActivity>(activityRef);
MyHandler
之外的类不需要知道Activity
已保存到Reference
。这是仅与MyHandler