Memory leak: Refers to memory not being collected in a timely manner by GC, resulting in excessive memory consumption. Thus causing the program to crash, which is often said Oom.
First, static
First look at the following code
public Class DBHelper {private static dbhelper db= null ; private dbhelper () {} public static dbhelper getinstance (Context context) {if (bitmaputils = = null ) {synchronized (dbhelper.class) {if (d b== null ) {db= new db (Context,dbna ME); }}} return db; }}
This code is not common in projects. Let's say we have a little detail. Should be able to find out where the problem is.
The helper holds the context application. And DBHelper is global, that is, when DBHelper is used in an activity, even if the activity exits, the activity cannot be recycled by GC. This causes the activity to reside in memory.
This solution is also simpler, code such as the following
public Class DBHelper {private static dbhelper db= null ; private dbhelper () {} public static dbhelper getinstance (Context context) {if (bitmaputils = = null ) {synchronized (dbhelper.class) {if (d b== null ) {db= new db (Context.geta Pplicationcontext (), DBNAME); }}} return db; }}
Only need to change the context to ApplicationContext (), because ApplicationContext itself is the global.
Second, non-static internal class, Handler
Take a look at the code first
PrivateHandler Handler =NewHandler () {@Override Public void DispatchMessage(Message msg) {//Message processing} };@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);NewThread (NewRunnable () {@Override Public void Run() {//time-consuming OperationHandler.sendemptymessage (1); }}). Start (); }
We know that non-static inner classes hold references to external classes, where handler holds references to external activity, and when we do asynchronous time-consuming operations in an activity's inner class, our activity assumptions are now erased, Asynchronous tasks do not end up running, which causes our activity objects not to be collected in a timely manner by GC, causing memory problems.
This kind of problem is very easy to solve.
- Do not perform asynchronous operations in anonymous inner classes
- Using static anonymous inner classes
Summary: Most of the memory problems are caused by the unfortunate processing of the object's life cycle. When an object is being used. We need to study the life cycle of the object carefully. When dealing with objects that occupy large memory and have longer lifecycles. The app can handle it with a soft reference. Close unused resources in a timely manner.
Android Memory leaks