Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a weak reference to the activity?

Tags:

android

kotlin

I was trying to implement a main handler for an android class.
How do I instantiate MyHandler object with the weak reference of the activity?

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
                }
            }
        }
    }
}
like image 850
Peter Hwang Avatar asked Oct 19 '25 09:10

Peter Hwang


1 Answers

I think it's better to directly pass the Activity instance in the constructor and just do

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

Classes outside of MyHandler do not need to know that the Activity is saved into a Reference. This is an implementation detail relevant only to MyHandler

like image 67
Marko Pacak Avatar answered Oct 22 '25 01:10

Marko Pacak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!