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
applicationContextfor databases, preferences, receivers and system services. - Dependency injection frameworks such as Hilt provide
@ApplicationContextso you do not pass it by hand.
