There are so many articles about memory leaks that there is no point in copying someone else’s. To recap, OnClickListener is an anonymous inner class that doesn’t cause a memory leak in Android. The reason for the MemoryLeak is that the instance of class (A) with A long lifetime is referenced by the instance of class (B) with A short lifetime, which is still referenced by A when B has finished its lifetime and needs to be released. As A result, B cannot be GC, resulting in MemoryLeak. The root cause is the old and classic saying: not released. Static variables: such as passing an activity instance to a static declaration variable. 2 Single instance: A single instance refers to something (such as an activity, or an activity context). 3 array: For example, if an array contains an activity, onDestroy will be destroyed if the activity goes away, but there are still references in the ArrayList that can’t be recycled. 4 Non-static inner class: A non-static inner class may have references to external classes and may be referenced by the inner class after the end of the life cycle of the external class. 5 Cursor, stream Are not closed. Basic is above 5 kinds of solutions, many online.

The most interesting thing to consider is that 4 non-static inner classes cause memory leaks. I’m curious to know that the OnClickListener we use a lot is a non-static inner class that almost never causes memory leaks. Why? 1. OnClickListener is an anonymous inner class that must have a reference to an external class. 2 And the OnClickListener that comes out of this new is referenced by who? The view that setOnClickListener (let’s call it viewC). 3 When the activity is destroyed, all views it contains will also release all references to their objects, including viewC, which will also release OnClickListener. OnClickListener refers to an activity, but it is no longer referenced by any object and can not reach the root according to the GC algorithm. How’s that? Amazing, isn’t it? That’s how it works.

The original link: blog.csdn.net/changqijihu…