0

I have read that using asynctask as an inner class of an activity will cause memory leaks because it won’t let the activity get garbage collected and also due to implicit referencing as well. Will the same memory leaks occur if we used different approaches like:-

  • Using AsyncTask in a seperate class ?
  • Or if we used AsyncTask with a headless fragment (using its setRetainInstance(true) method to avoid its destruction).

I have implemented the headless fragment approach and it works great since the asynctask object is created only once and its controlled by the headless fragment but i can’t figure out if the memory leak of the activity problem is gone or if its still there.

syed_noorullah
  • 155
  • 2
  • 13

1 Answers1

1

First of all you could use a library as LeakCanary or learn how to use the android profiler to find leaks. Consider that not every expert agrees that small leaks have to be fixed, some of them are really small and won't cause big troubles.

the headless fragment approach should be good. To reply to your first question, consider that you can make static the inner class as indicated here where is explained also how to make a weak reference that would be easily garbage collected

trocchietto
  • 2,607
  • 2
  • 23
  • 36
  • I came up with an alternative of AsyncTask which is Loaders but found out that it has become deprecated due to some issues. The Android documentation suggests using MVVM as an alternative. I studied what it was and found out that using AsuncTask + MVVM is lifecycle friendly, neat and saves memory leaks. Will try it. What do you think about it ? – syed_noorullah May 25 '19 at 16:02
  • 1
    eh eh Loaders and even AsyncTask are quite old school, have a look to LiveData and RXJava. But first LiveData, that RXJava is really difficult for principiants – trocchietto May 25 '19 at 16:04
  • I studied about LiveData when I was studying about MVVM. What I understood was it’s a data wrapper which can be observed through the view(I.e Activities). It not only contains data for the view but also coordinates/syncs with it. I don’t know about RxJava but I do know that people are suggesting Retrofit as well. I am a beginner student in Android so I’ve just started exploring this :) – syed_noorullah May 25 '19 at 17:43
  • Man LeakCanary is great :) Most of my doubts that about memory leaks are clear now thanks to this :D – syed_noorullah May 25 '19 at 20:52
  • you are really welcome, (memory leaks sometimes can be really troublesome and depending from libraries or SDK), please so accept my reply as answer then – trocchietto May 26 '19 at 18:10