When I've used handlers in Android before using java I would get an Android Studio lint message saying that I should use a static handler, otherwise memory leaks will occur. Since Kotlin has no static keyword, how should I handle it? Here is my class:
class TaskDetailActivity : AppCompatActivity() {
private val handlerComment = MyOptionMenuBarHandler(this)
private fun setUpToolBar() {
handlerComment.sendEmptyMessage(0)
}
private class MyOptionMenuBarHandler(activity: TaskDetailActivity) : Handler() {
private val activity: WeakReference<TaskDetailActivity> = WeakReference<TaskDetailActivity>(activity)
override fun handleMessage(msg: Message) {
//do the work
.....
}
}
}
Is there anything special I need to do to avoid memory leaks using Kotlin?
One should not use static views while developing the application, as static views are never destroyed. One should never use the Context as static, because that context will be available through the life of the application, and will not be restricted to the particular activity.
To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.
Lint tells you to mark your inner Handler
class as static
to prevent compiler from adding the reference of enclosing class into the Handler
implementation (it adds it by default to all inner non-static classes), because this might create a memory leak.
Now, Kotlin has notions between inner
and nested
class. The nested
class is what you get by default if you declare some class Foo
inside another class. The nested classes do not have the implicit reference to enclosing class (they're similar to the Java's inner static classes in that regard). Your MyOptionMenuBarHandler
class is exactly that.
If you want to add the reference to enclosing class to your inner class, you can mark it as inner
.
In short:
inner
.static
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With