存储静态应用程序类是内存泄漏吗?

时间:2019-07-10 13:52:14

标签: android memory-leaks

在我的项目的以下示例代码中,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);
    }
}

1 个答案:

答案 0 :(得分:1)

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

如果它是一个活动上下文,那么它将非常容易泄漏。应用程序上下文是应用程序范围内的单例,它不会导致泄漏。您可以根据需要忽略或取消此警告。

static状态是一种反模式,因此大多数时候最好还是避免这种情况。

相关问题