---
title: "How do you get the application context in Android without leaking an Activity?"
description: "Use applicationContext for long-lived objects. Holding an Activity context in a singleton or static field leaks the whole screen."
url: "https://bugsee.com/answers/android/get-the-application-context/"
---

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

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.

```kotlin
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

- [How do you fix NetworkOnMainThreadException in Android?](https://bugsee.com/answers/android/fix-network-on-main-thread-exception/)
