Sobes.tech
Junior — Middle

Can you give examples of situations or factors that can lead to memory leaks in Android applications?

sobes.tech AI

Answer from AI

Main causes of memory leaks in Android applications:

  • Long-lived references to Activity or View contexts. For example, static variables that hold a reference to an Activity prevent it from being garbage collected.

  • Incorrect use of listeners and callbacks. If a listener is not unregistered, it can hold a reference to an object.

  • Use of anonymous inner classes and lambdas that implicitly hold a reference to the outer class.

  • Incorrect resource management, such as unclosed Cursor, InputStream, Bitmap.

  • Using Handlers with delays or messages that reference an Activity but are not cleared upon destruction.

  • Caching large objects without size limits.

Example of leak due to static reference:

class MyActivity : AppCompatActivity() {
    companion object {
        var leakedReference: MyActivity? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        leakedReference = this // Activity will not be released
    }
}

To avoid leaks, it is important to properly manage the lifecycle of objects and release resources.