Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static equivalent in Android for kotlin to avoid handler memory leaks

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?

like image 398
Kristy Welsh Avatar asked Jan 04 '18 15:01

Kristy Welsh


People also ask

What are some best practices to avoid memory leaks on Android?

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.

Which of the following options need to be followed to avoid memory leaks?

To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.


1 Answers

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:

  1. Kotlin and Java have different defaults in regard to inner class. In Kotlin the inner class does not have reference to enclosing class by default, in java it does.
  2. If you want to have implicit reference to outer class in Kotlin, mark inner class as inner.
  3. If you don't want to have such reference in Java, mark inner class as static.
like image 198
aga Avatar answered Oct 10 '22 20:10

aga