Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Potential causes of memory leaks in Android

I'm using leakcanery to find memory leaks in Android. I found and fixed all Activity leaks. (surprised to know there were so many BTW!). I also added watch refWatcher for all my Fragments.

Question 1: Is there anything else that I should watch that may cause noticeable memory leak?

Question 2: Isn't watching Fragment leaks redundant since a Fragment holds a reference to its Activity? I get the notification anyway, right? :-/

Question 3: When I check the memory monitor in android studio it shows the memory usage growth over time. Is it a sign of a giant memory leak or Android OS is kind and it is just giving me more memory? How can I find for sure?

like image 755
Alireza A. Ahmadi Avatar asked May 25 '15 05:05

Alireza A. Ahmadi


1 Answers

Is there anything else that I should watch that may cause a noticeable memory leak?

  • Declaring a member field static almost guarantees a memory leak.
  • Anonymous classes that last beyond the lifetime of the parent class, such as Volley Requests, also produce memory leaks, because they hold an implicit reference to the parent Activity, and if the Activity is gone before the request call completes, a memory leak takes place.

Isn't watching Fragment leaks redundant since a Fragment holds a reference to its Activity?

A Fragment doesn't "hold" a reference to an Activity. The reference is supplied by the FragmentManager. But the framework manages this internally, so you don't need to worry about it.

When I check the memory monitor in android studio it shows the memory usage growth over time. Is it a sign of a giant memory leak or Android OS is kind and it is just giving me more memory? How can I find for sure?

The memory growth of an app is natural, and the memory is cleaned up on subsequent passes of the garbage collector. In languages that have virtual machines and automatic garbage collectors, the programmer has little to no control over the allocation of memory. Beyond creating tiny memory leaks, there is very little a programmer can do to screw up the memory management process.

like image 131
Y.S Avatar answered Oct 02 '22 11:10

Y.S