简体   繁体   中英

Why does simple example using Activity in Android cause a memory leak?

I got the following example and Im not sure why this is causing a memory leak? I can not wrap my head around it?!

public class MyLeakActivity extends Activity {

// static reference to evil

   private static final Evil e;   
   public MyLeakActivity() {
     e = new Evil();
   }

private final class Evil {
      }
}

Thanks in advance.

greetings Fabian

Take a look here ... this article is geared toward Android development.

https://dzone.com/articles/a-troublesome-legacy-memory-leaks-in-java

  • Avoid using non-static inner classes in your Activities, use a static inner class and make a WeakReference.

I think your design might never allow the enclosing class to be gc'd. Unless you have a very good reason to use a non-static inner class (maybe for scope reasons,) a good rule of thumb is to always begin with the inner class declared as static.

在创建新对象之前,您应该检查 e == null 是否。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM