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.
You have 2 sources of leaks in your code:
applicationContext
instead of context
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