Peter Hwang
Peter Hwang

Reputation: 991

How to pass a weak reference to the activity?

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
                }
            }
        }
    }
}

Upvotes: 4

Views: 4398

Answers (1)

payloc91
payloc91

Reputation: 3809

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

Upvotes: 11

Related Questions