警告 - 内存泄漏 - 静态字段中的上下文类

时间:2017-10-21 17:13:43

标签: java android memory-leaks

我正在尝试从Codelabs实现架构组件。但我收到以下错误

  

不要将Android上下文类放在静态字段中(静态   引用具有字段mContext指向的FarmerNetworkDataSource   到上下文);这是内存泄漏(也打破了Instant Run)   少...

我直接使用Google Codelabs的代码段。你可以refer it here

我见过一些duplicate questions。但我无法弄清楚哪个是最好的实践。

请帮助&引导我......

CODE

public class FarmerNetworkDataSource {

    // For Singleton instantiation
    private static final Object LOCK = new Object();
    private static FarmerNetworkDataSource sInstance;
    private final Context mContext;

    private final AppExecutors mExecutors;

    private FarmerNetworkDataSource(Context context, AppExecutors executors) {
        mContext = context;
        mExecutors = executors;
    }

    /**
     * Get the singleton for this class
     */
    public static FarmerNetworkDataSource getInstance(Context context, AppExecutors executors) {
        Log.d(LOG_TAG, "Getting the network data source");
        if (sInstance == null) {
            synchronized (LOCK) {
                sInstance = new FarmerNetworkDataSource(context.getApplicationContext(), executors);
                Log.d(LOG_TAG, "Made new network data source");
            }
        }
        return sInstance;
    }
}

REPOSITORY

public static FarmerRepository provideRepository(Context context) {
        AppExecutors executors = AppExecutors.getInstance();
        FarmerNetworkDataSource networkDataSource =
                FarmerNetworkDataSource.getInstance(context.getApplicationContext(), executors);
        return FarmerRepository.getInstance(networkDataSource, executors);
    }

1 个答案:

答案 0 :(得分:3)

我的方法是:

private static WeakReference<Context> appContext;

public static Context getAppContext() {
    if (appContext == null)
        return null;
    return appContext.get();
}
  

WeakReference 影响垃圾收集器。大多数对象都是   引用必须保留在内存中,直到它们无法访问。但随着   WeakReference,可以收集引用的对象。

我在几个项目中使用它,事实证明它非常方便。