How to optimize memory leaks, after reading this blog, you will be able to deal with it with ease! ! !

In short:

       During our development, it is easy to cause memory leaks in the app, so what is a memory leak, how do we solve it, and how to optimize the memory leak?

1. What is a memory leak?

If an object is still being referenced by other objects when it is not needed, the object cannot be recycled, and the object cannot be released, resulting in a waste of space and memory. This situation is a memory leak.

2. What are our common memory leaks?

1) Memory leak caused by static variables:

Static variables are stored in the method area, and its life cycle starts from the beginning to the end of class loading. Once the static variable is initialized, the reference it holds will not be released until the process ends.

In many cases, static holding may cause memory leaks due to the inconsistent life cycle of its use, so when we create static holding variables, we need to consider the reference relationship between various members, and use static holding as little as possible. Some variables to avoid memory leaks. Of course, we can also reset the static value to null at an appropriate time so that it no longer holds a reference, which can also avoid memory leaks.

We look at a piece of code:

    public class MainActivity extends Activity{
    	public static Context mContext;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		mContext = this;
    	}
    }

If the Context object is static, then the Activity cannot be destroyed normally and will stay in memory.

Solution:

Use Application Context. 2 Use static keyword with caution

 

2) Non-static internal classes cause memory leaks

The non-static inner class will hold the reference of the outer class by default. When the life cycle of the non-static inner class object is longer than the life cycle of the outer class object, it will cause memory leakage.

The use of Handler is typical:

The handler will implicitly hold the external reference of the current class. Because the Handler is a non-static internal class, it holds the implicit reference of the current Activity. If the Handler is not released, the external reference held by it, that is, the Activity, cannot be released. , When an object does not need to be used anymore, it should be recycled, and another object in use holds its reference, which makes it unable to be recycled, which causes the object that should have been recycled cannot be recycled and stays In the heap memory, this creates a memory leak.

How to use the handler? Show by code:

public class MainActivity extends AppCompatActivity{ 

private Handler mHandler;

 @Override 
protected void onCreate(BundlesavedInstanceState){ 

super.onCreate(savedInstanceState); 

setContentView(R.layout.activity_main);

 mHandler=newMyHandler(this);

start();
}
private void start(){ 

Messagemsg=Message.obtain();

msg.what=1;

mHandler.sendMessage(msg);

}


private static class MyHandler extends Handler{

private  WeakReference<MainActivity> activityWeakReference;

public MyHandler(MainActivity activity){ 

activityWeakReference=newWeakReference<>(activity);

}
@Override
public void handleMessage(Messagemsg){

MainActivityactivity=activityWeakReference.get();

if(activity!=null){

if(msg.what==1){

//做相应逻辑
         }
       }
    }
  }
}

mHandler holds the Activity through weak references. When the GC performs garbage collection, it will reclaim and release the occupied memory unit when it encounters the Activity. In this way, memory leaks will not occur.

 

3) TimerTask causes memory leak

When our Activity is destroyed, it is possible that the Timer is still waiting to execute the TimerTask. It holds the reference to the Activity and cannot be recycled. Therefore, when our Activity is destroyed, we must immediately cancel the Timer and TimerTask to avoid memory leaks.

 

4) The objects in the collection are not cleaned up causing memory leaks

If an object is placed in a collection such as ArrayList, HashMap, etc., this collection will hold a reference to the object. When we no longer need this object, we did not remove it from the collection, so as long as the collection is still in use (and this object is useless), this object causes a memory leak. And if the collection is statically referenced, those useless objects in the collection will even cause memory leaks. Therefore, when using the collection, remove or clear the unused objects from the collection in time to avoid memory leaks.

5) The resource is not closed or released causing memory leaks

When using IO, File stream or Sqlite, Cursor and other resources, it must be closed in time. These resources usually use buffers during read and write operations. If they are not closed in time, these buffer objects will remain occupied and cannot be released, resulting in memory leaks. Therefore, we close them in time when we don't need to use them, so that the buffer can be released in time to avoid memory leaks.

6) Memory leak caused by attribute animation

Animation is also a time-consuming task. For example, when the property animation (ObjectAnimator) is started in the Activity, the cancle method is not called when it is destroyed. Although we can't see the animation anymore, the animation will continue to play. The control where the reference is located refers to the Activity, which causes the Activity to be unable to be released normally. Therefore, it is also necessary to cancel the attribute animation when the Activity is destroyed to avoid memory leaks.

to sum up:

Memory leak is a more important aspect in Android memory optimization. In summary, as long as you do the following points, you can avoid memory leaks in most cases:

Pay attention to the blanking of application objects or use less static references when static references;

Use static inner classes + soft references instead of non-static inner classes;

Cancel broadcast or observer registration in time; remember to cancel time-consuming tasks and attribute animations when Activity is destroyed;

File stream, Cursor and other resources are closed in time;

 

Guess you like

Origin blog.csdn.net/wk_beicai/article/details/109491317