Android : References to a Context and memory leaks

前端 未结 2 2023
误落风尘
误落风尘 2020-12-04 18:18

I\'ve read that it is a mistake and a source of memory leaks in Android application to keep a long-lived references to a Context.

But I don\'t understand if it is ok

相关标签:
2条回答
  • 2020-12-04 18:47

    This is fine, and will not cause a memory leak.

    As soon as onCreate finishes executing, h will be out of scope and become eligible for garbage collection. If h was static, then you would run into problems. Only when the reference to the context outlives the lifecycle of the context itself will a memory leak occur. A few helpful hints:

    • Use Context.getApplicationContext() when possible. This context will live as long as your application is alive.
    • Be careful when using static fields and inner classes.
    • Run your application through a profiler to check for leaks.
    0 讨论(0)
  • 2020-12-04 18:48

    The scope of the HelperClass is only within your onCreate function, so once onCreate executed, your "h" object is no longer needed and subject to garbage collection.

    It would be a different story if "h" was a static member - THAT would be a great way to leak memory.

    0 讨论(0)
提交回复
热议问题