How do you get the application context in Android without leaking an Activity?

← Android answers

Call context.applicationContext, or inject the Application, whenever an object outlives a screen. Never store an Activity as a static or singleton field.

An Activity context is tied to one screen. If a singleton, a static field or a long-running task holds it, the system cannot garbage collect the Activity and all of its views after the screen closes.

class Analytics private constructor(private val appContext: Context) {
    companion object {
        @Volatile private var instance: Analytics? = null
 
        fun get(context: Context): Analytics =
            instance ?: synchronized(this) {
                instance ?: Analytics(context.applicationContext).also { instance = it }
            }
    }
}
  • Use the Activity context for anything that shows UI: dialogs, themed inflation and starting activities with a task you expect to be scoped to that screen.
  • Use applicationContext for databases, preferences, receivers and system services.
  • Dependency injection frameworks such as Hilt provide @ApplicationContext so you do not pass it by hand.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required