且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除片段后内存未释放

更新时间:2023-02-02 21:09:48

垃圾收集有时是 Android 中的一个痛苦问题.大多数开发人员没有考虑这个问题,只是在没有任何资源分配意识的情况下继续开发.

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.

这当然会导致内存泄漏、OOM 和不必要的资源绑定等内存问题.绝对没有自动释放内存的方法.在任何情况下,您都不能仅仅依赖垃圾收集器

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

每当您传递 Fragment 或 Activity 的 onDestroy() 方法时,您可以而且应该做的是删除应用程序中不再需要的任何构造.您可以执行以下操作:

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. 避免匿名监听器实例.创建侦听器并在您不再需要它们时销毁它们.
  2. 将所有侦听器(单击、长按等)设置为 null
  3. 清除所有变量、数组.对包含在 Activity/Fragment 中的所有类和子类应用相同的过程
  4. 每当您对给定的类执行任何前面的步骤时,将变量设置为 null(适用于所有变量)

我最终做的是创建一个类似的界面

What I ended up doing was creating an interface like

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

并在每个类上实现它,无论是 Activity、Fragment 还是普通类(包括适配器、自定义视图等).

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.