1

I created a custom Application class for my app. This class onCreate sets a static variable of itself like this

public void onCreate() {
  super.onCreate();
  mInstance = this;
}
public static ChattyApp getInstance() {
  return mInstance;
}

Then I use App.getInstance() method to get application context to a nonactivity/fragment class like API Controller or something. Can it cause a memory leak?

I setup leak canary and it is showing memory leak on an instance variable of Application class. This variable keeps socket.io's socket ref so that I can use it anywhere in the app.

1 Answers1

1

It is a good question that you have asked and people on SO have had extensive discussions on this. Have a look at this and this

Although this seems to be an okay way to store the Context in Application class as per the discussion in the first link, there can be better ways to deal with this.

Ideally for each logic unit you should have a separate class to deal with it rather than polluting your application class. You application class can however initialize or setup those other classes. This will create a separation of concern.

Another way is to use Dagger2, which is a dependency injection framework, to inject your socket ref to wherever you want.

Dagger 2 has a steep learning curve and but a very important tool to learn as an Android developer

kerry
  • 2,362
  • 20
  • 33
  • Yes, dagger is a good way to go and I am planning to upgrade to that but right now it not optimal for me to do it. And the learning curve will take some time. – Shahid Helal Jun 19 '19 at 06:52
  • Then you can use the first method – kerry Jun 19 '19 at 06:53
  • Thanks, I got it fixed I think. I turned off all socket listener every time in onDestroy. And replaced the getInstance method to take a context and just cast the context to the Application class rather than keeping a static ref. I am not sure which once solved the issue. – Shahid Helal Jun 19 '19 at 13:23