如何避免内存泄漏?

How to avoid memory leak here?

我正在创建一个模块(一组 类 来执行功能),我需要上下文对象来执行一些操作,例如安全设置读取和其他操作。

我不喜欢为我的 类 创建多个对象,这在我的情况下是不需要的,即使我正在做这样的事情,

class MyModuleFactory {

    private static final String TAG = MyModuleFactory.class.getSimpleName();
    public Context mContext;
    private static HashMap<Context, MyModuleFactory> myInstance = new HashMap<>();

    private MyModuleFactory(Context context) {
        mContext = context;
    }

    public static synchronized MyModuleFactory getInstance(Context mContext) {
        if(mContext == null) {
            Log.i(TAG, "Context cannot be null");
            return null;
        }
        if(myInstance.get(mContext.getApplicationContext()) != null) {
            return myInstance.get(mContext.getApplicationContext());
        } else {
            MyModuleFactory myModuleFactory = new MyModuleFactory(mContext);
            myInstance.put(mContext.getApplicationContext(), myModuleFactory);
        }
    }
}

我担心的是因为我在这里持有应用程序的上下文,我担心我会导致内存泄漏 - 原因是因为 Android 可以随时清除应用程序对象并重新创建它。因此,在应用程序的生命周期后面保留上下文并且不允许在此处清除上下文可能会导致内存泄漏。

在此处为我的模块强制单例并避免内存泄漏的更好方法是什么。

如果您持有对应用程序上下文的引用,则不会有任何内存泄漏。只要应用 运行,应用上下文就会存在。当应用程序被杀死时,它会被销毁。那样的话,连你的单例都会被销毁,所以不会发生内存泄漏。

只需确保您仅持有对单例中应用程序上下文的引用,而不是 Activity 上下文。

查看this post了解详细信息:

If you have to create a singleton object for your application and that object needs a context, always pass the application context.

If you pass the activity context here, it will lead to the memory leak as it will keep the reference to the activity and activity will not be garbage collected.