【发布时间】:2019-07-10 13:52:14
【问题描述】:
在我项目的以下示例代码中,android studio 警告我这是内存泄漏。 Android Studio 对吗? 应用程序类是单例的,因此我认为将它存储在我的类中是件好事。你有什么建议?
public class MyApi {
private static MyApi instance ; // Compiler gives the following warning: Do not place Android context classes in static fields (static reference to MyApi which has field context pointing to Context); this is a memory leak
private Context context; // i need this context inside MyApi class.
public static MyApi getInstance() {
return instance;
}
public static void init(Context context) {
instance = new MyApi(context);
}
private MyApi(final Context context) {
this.context = context;
}
}
public class App extends Application{
@Override
public void onCreate() {
MyApi.init(this);
}
}
【问题讨论】:
-
将
MyApi中对Context的所有引用更改为Application。从内存泄漏的角度来看,您的代码很好......除了其他东西可以调用init()和一些Context,而不是Application。 -
我的 App 类从 MultiDexApplication 扩展而来。我应该更改对 Application 或 MultiDexApplication 的所有引用吗?
标签: android memory-leaks