我一直在阅读一些关于 Android 中单例模式的使用及其在保持上下文方面的缺点。事实上,当我实现下面的代码时:
private static HttpManager sSingleton;
private Context mContext;
private HttpManager(Context context) {
mContext = context;
}
public static synchronized HttpManager getInstance(Context context) {
if (sSingleton == null) {
sSingleton = new HttpManager(context);
}
return sSingleton;
}
Android Studio 向我显示以下警告:
Do not place Android context classes in static fields (static reference to HttpManager which has field mContext pointing to Context); this is a memory leak and also breaks Instant Run.
但是,我可以看到 Singletons 已实现并被推荐 in this page of Android's docs .
If your application makes constant use of the network, it's probably most efficient to set up a single instance of RequestQueue that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality.
由于谷歌自相矛盾,有人可以在这一点上指导我并给我建议吗?
最佳答案
Since Google is contradicting itself
不,不是。
引用的 Lint 警告并不是在提示创建单例。它提示创建持有对任意 Context
的引用的单例,因为这可能类似于 Activity
。希望通过将 mContext = context
更改为 mContext = context.getApplicationContext()
,您将摆脱该警告(尽管这可能仍然会破坏 Instant Run — 我无法对此发表评论)。
创建单例是可以的,只要您非常小心地这样做,以避免内存泄漏(例如,持有对 Activity
的无限期 static
引用)。
关于java - Android——谷歌对单例模式的矛盾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39840818/