Sobes.tech
Junior — Middle

What methods can be used to prevent memory leaks in applications?

sobes.tech AI

Answer from AI

Memory leaks in Android applications can be prevented by:

  • Releasing resources: always close Cursor, InputStream, OutputStream, and other resources after use.
  • Avoiding strong references to Context: do not store references to Activity or Context in static variables to prevent garbage collection issues.
  • Using WeakReference: for objects that should not prevent garbage collection.
  • Unregistering listeners and callbacks: when destroying Activity or Fragment, unregister all listeners to avoid holding references.
  • Checking for cyclic references: especially with anonymous classes and lambdas.
  • Using profilers: Android Profiler, LeakCanary for detecting and analyzing leaks.

Example of using WeakReference:

class MyClass(context: Context) {
    private val contextRef = WeakReference(context)

    fun doSomething() {
        val ctx = contextRef.get()
        ctx?.let {
            // work with context
        }
    }
}