Article From:

Please think, why can the memory leak?

 1. First, the non static inner class will hold the reference of the external class by default.

 2. Then, a static instance is created by using the non static internal class.

 3. The life cycle of this static instance is as long as that of the application, which causes the static instance to hold the reference of the Activity, causing the memory resources of the Activity to not be recovered normally.

There are two correct approaches, one is to change the internal class testResource into a static internal class, and the other is to extract the testResource and encapsulate it into a single example, as in the previous example, but when the context is required, a single case should be taken to note the Contex.T leakage, use applicationContext.

Here, we directly change testResource into static internal class. The code is as follows


Leave a Reply

Your email address will not be published. Required fields are marked *