2

I often see advice like "Don't do X this way or else you risk leaking the Activity / Context."

I don't actually know what "leaking" means or how to know that you're at risk of leaking. Can anyone elaborate?

UxDude
  • 43
  • 3
  • Can you provide more context? –  Jul 05 '17 at 18:59
  • http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html https://android-developers.googleblog.com/2009/01/avoiding-memory-leaks.html – tyczj Jul 05 '17 at 19:01
  • See also https://www.toptal.com/java/hunting-memory-leaks-in-java and https://stackoverflow.com/q/6470651/115145 and https://plumbr.eu/blog/memory-leaks/what-is-a-memory-leak and... – CommonsWare Jul 05 '17 at 19:01

1 Answers1

8

Leaking means you are creating a situation where an object can't be garbage collected - so even though the activity has gone away, it's still in memory and can't be cleaned up - i.e. you are wasting memory unnecessarily (called a memory leak).

Basically what it means, in this case, is don't create references to activities that will prevent the activities from being garbage collected when they are done. Avoid assigning the context or activity to a variable in another activity, class, service, etc.. or if you must have the context, consider using a weak reference.

i.e. don't store a strong reference to an activity in a static class, don't use a strong reference to an activity in a long running process, etc.

jt-gilkeson
  • 2,661
  • 1
  • 30
  • 40