HyeonSeok
HyeonSeok

Reputation: 599

Can handler class with activity's context cause memory leak?

I'm wondering if class extends Handler with activity's context in it's constructor may cause memory leak.

This is my code about that.

class MyActivity : AppCompatActivity() {

    class HandlerWithContext(private val context: Context) : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            //Do something with context
        }
    }

    private val handlerWithContext = HandlerWithContext(this)

    private fun runMyHandler() {
        handlerWithContext.postDelayed({

        }, 10000)
    }
}

I guess it cause memory leak because HandlerWithContext holds activity's context.

But How to deal with activity's context in this case?

Thanks.

Upvotes: 1

Views: 472

Answers (1)

Shivam Pokhriyal
Shivam Pokhriyal

Reputation: 1104

You have 2 sources of leaks in your code:

  • Using context outside the activity lifecycle. You can avoid this by using applicationContext instead of context
  • Additionally, the anonymous class you are using with handler.postDelayed holds a reference to the your activity. So you'll need to remove that in onDestroy like this:
    override fun onDestroy() {
        super.onDestroy()
        handlerWithContext.removeCallbacksAndMessages(null)
    }

Lastly, use leakcanary to detect leaks in your code. Here's the getting started guide

Upvotes: 2

Related Questions