Memory not freeing after fragment is removed

谁说胖子不能爱 提交于 2019-11-29 02:03:00

Garbage Collection is sometimes a painful issue in Android. Most developers fail to consider this issue and just keep developing without any sense of resource allocation.

This will of course cause memory problems such as leaks, OOM and unnecessary resource binding. There is absolutely no automatic way to free up memory. You can not, under any circumstances, rely solely on the Garbage Collector

Whenever you pass the Fragment's or Activity's onDestroy() method, what you can and should do is erase any construct that shall no longer be required in the application. You can do the following :

  1. Avoid anonymous instances of listeners. Create listeners and destroy them when you no longer need them.
  2. Set all the listeners (be them click, longclick, etc) to null
  3. Clear all variables, arrays. Apply the same procedure to all the classes and subclasses contained inside the Activity/Fragment
  4. Set the variable to null whenever you perform any of the previous steps on that given class (applies to all variables)

What I ended up doing was creating an interface like

public interface clearMemory(){
    void clearMemory();
}

and implementing it on every class, be it Activity, Fragment or a normal class (includes adapters, custom views, etc).

I would then call the method whenever the class was to be destroyed (because the app was being destroyed or whenever I felt need to do so. Careful not to dispose in normal runtime)

@Override
public void onDestroy(){
    clearMemory();
}

public void clearMemory(){
    normalButtonOnClickListener = null;
    normalButton.setOnClickListener(null);
    normalButton = null;
    myCustomClass.clearMemory(); // apply the interface to the class and clear it inside
    myCustomClass = null;
    simpleVariable = null;
    ...        
}

By implementing this in a systematic way, my applications' memory management has become easier and leaner. One can then then know/control exactly how and when the memory is disposed.

This is adding on to Ricardo's answer.

You can add the following code to initiate garbage collection in Android:
Runtime.getRuntime().gc();

Note: Call this function after you've made all local variables null. Execution of this code doesn't guarantee that the system will garbage collect on your app, it merely hints that it might be a good time to do it.
I've used this in all my activities' onDestroy(), and it always seems to work when I want it to.
Give it a try, it might help you out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!