Reputation: 5925
In the below example code from my project, android studio warns me that this is a memory leak. Is Android Studio right? Application class is singleton thus i thought that it is good to store it in my class. What is your suggestions?
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);
}
}
Upvotes: 0
Views: 300
Reputation: 152807
Lint sees you store a Context
in a static
. It does not know which kind of context it is.
If it was an activity context, then it would be super easy to leak. Application context is an application-scoped singleton and it does not cause a leak. You can ignore or suppress this warning if you want to.
static
state is kind of an anti-pattern so most of the time you're better of avoiding it though.
Upvotes: 1