Square Leakcannary has recently taken a look at a number of memory leaks that might not have been noticed. Let’s talk about the causes of memory leaks and the solutions.
Memory leaks: Some objects have a limited life cycle and will be garbage collected when they have completed their tasks. If the object continues to be referenced by a series of references after the end of its life cycle, this will result in a memory leak. As leaks accumulate, the App will eventually run out of memory.
Memory leak: It is one of the most important reasons for the OOM application. Android has a limited amount of memory allocated to each application. A large number of memory leaks in an application can cause the current application to occupy more memory than the system allocates by default. This causes the class memory to overflow, which leads to OOM.
Instructions for leakCannary are linked below.
LeakCanary Instructions in Chinese
1. Memory leakage caused by incorrect use of singleton mode
The singleton pattern is indispensable in development. A memory leak may occur if the context held in a singleton has a shorter lifetime than the singleton or the context cannot be released. The solution is to ensure that the Context and Application lifecycles are consistent.
2. Memory leakage caused by Handler
Development inevitably uses handlers to pass messages. Handlers are typically created as inner classes, and inner classes hold references to outer classes by default. When the Activity is destroyed and the handler still has messages to send, the Handler calls the POST method and loads a Message and pushes the Message to the MessageQueue. MessageQueue is polling for messages in a Looper thread, so when the Activity exits there are unprocessed or processed messages in the Message queue, and Message in the Message queue holds references to mHandler instances. MHandler also holds a reference to the Activity, so the Activity’s memory resources cannot be reclaimed in time, causing a memory leak. Fixing memory leaks caused by handlers is simple. 1.Handler declares static and weakly references Activity 2. Call handler’s removeAllCallBacks method during Activity onDestory ().
3. Memory leaks caused by non-static inner classes
Memory leaks can also occur when external class objects need to be released and when internal class objects need to be used at any time. The solution is to make the inner class life static. Or use inner classes less.
Late supplement…