[英]Warning - Memory Leak - Context classes in static fields
I am trying to implement Architecture Components from Codelabs. 我正在尝试从Codelabs实现架构组件。 But I'm getting the below error
但我得到以下错误
Do not place Android context classes in static fields (static reference to FarmerNetworkDataSource which has field mContext pointing to Context);
不要将Android上下文类放在静态字段中(静态引用FarmerNetworkDataSource,其中字段mContext指向Context); this is a memory leak (and also breaks Instant Run) less...
这是一个内存泄漏(也打破了瞬间运行)少...
I used the code snippet directly from Google Codelabs. 我直接使用Google Codelabs的代码段。 You can refer it here
你可以在这里参考
I have seen some duplicate questions . 我看到了一些重复的问题 。 But i can't figure out which is the best pratice to follow.
但我无法弄清楚哪个是最好的实践。
Please help & Guide me... 请帮忙指导我......
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 REPOSITORY
public static FarmerRepository provideRepository(Context context) {
AppExecutors executors = AppExecutors.getInstance();
FarmerNetworkDataSource networkDataSource =
FarmerNetworkDataSource.getInstance(context.getApplicationContext(), executors);
return FarmerRepository.getInstance(networkDataSource, executors);
}
My way around it is: 我的方法是:
private static WeakReference<Context> appContext;
public static Context getAppContext() {
if (appContext == null)
return null;
return appContext.get();
}
WeakReference influences the garbage collector.
WeakReference会影响垃圾收集器。 Most objects that are referenced must be kept in memory until they are unreachable.
引用的大多数对象必须保留在内存中,直到它们无法访问。 But with WeakReference, objects that are referenced can be collected.
但是使用WeakReference,可以收集引用的对象。
I used it in a couple of projects and it proved to be very handy. 我在几个项目中使用它,事实证明它非常方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.