【问题标题】:Is storing static application class a memory leak?存储静态应用程序类是内存泄漏吗?
【发布时间】: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


【解决方案1】:

Lint 发现您将 Context 存储在 static 中。它不知道它是哪种上下文。

如果它是一个活动上下文,那么它会非常容易泄漏。应用程序上下文是一个应用程序范围的单例,它不会导致泄漏。如果您愿意,可以忽略或隐藏此警告。

static 状态是一种反模式,所以大多数时候你最好避免它。

【讨论】:

    猜你喜欢
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2012-11-04
    • 2014-10-25
    • 2016-03-28
    相关资源
    最近更新 更多