An overview of the
Android memory leak, also known as OOM(out of Memory), the consequences of OOM are known to all, seriously affecting the APP experience, the light will be delayed, or flash back. And memory leaks are usually accompanied by ANR on low-end machines, so it’s important to pay attention to.
Common causes of memory leaks are:
- IO operations
- Bitmap
- Context
- Singletons hold references
- Service
- BroadcastReceiver
- ContentObserver
- Handler
- Thread
Analysis method
Common methods for analyzing memory leaks:
- StrictMode,
Application
theonCreate
addStrictMode
The code block - Leakcanary, reference
Leakcanary
Library (Conventional means, for participation only, should not rely entirely on this library) - Monkey, simulate user click operation, check for leaks (recommended, most effective method)
- Adb command triggered manually
adb shell dumpsys meminfo packagename -d
- Android Studio Memory Profiler,
Android Studio
Own analysis tools, has been very easy to use - MAT, the ultimate artifact, the topic of Memory analysis (
Android Studio
Depending on it)
The solution
- Context
If you’ve ever collected crash logs for memory leaks, you’ll see that a lot of errors are caused by Context and Handler. Because we use a lot of Context references in development, and Context has instances of itself in Application, Activity, Service, and so on, and Activity and Service have Context instances that are recycled for lifecycle reasons, If you continue to use its references you will get an error due to weak references. References to Context are also common in the singleton pattern. So I recommend that you use the Application Context whenever possible.
- Bitmap
Problems with Bitmaps are usually caused by not releasing images in a timely manner. Images consume a lot of memory because of their size. The solution is to reclaim memory in onDestroy().
- IO operations
FileOutputStream() is not closed, THE IO stream forgot to close solution: Shut down the IO stream in time to avoid leakage
- Handler leak
Since the Activity is shut down and the Handler task has not completed, references to instances of the Activity result in a memory leak solution: Reclaim the Handler in the Activity’s onDestroy() method
- Asynchronous thread leakage
The solution is to extract the thread as an object and block it in the Activity’s onDestroy() method
- Static member variable
If you have a large number of static variable definitions and reference resources, be sure to release them in onDestroy or elsewhere (empty the variables).