Context: application vs activity
Why it matters
- Holding an Activity Context in a singleton, a ViewModel, or a long-running task keeps the whole Activity (and its View tree) in memory after it is destroyed. Enough of these leaks and the app runs out of memory.
- Interviewers ask "which Context do you give a ViewModel?" and "what breaks if you pass the wrong one?" as a quick filter for real debugging experience.
- Misusing Context is one of the most common causes of "retained Activity" reports in LeakCanary.
- Using the wrong Context the other way round also breaks things: a Dialog built from the Application Context crashes, and views inflated from it lose your Activity's theme.
The simple explanation
- Think of the Application Context as the building's main power line: it is there as long as the building (the process) is.
- Think of an Activity Context as one room: it has its own decoration (the theme) and a window, but only while the room is in use.
- If a permanent appliance (a singleton) keeps a wire into a room, the room can never be torn down, even after nobody uses it.
- The fix: plug permanent appliances into the main line (the Application Context), and use the room only for things that belong in the room.
A Context is a handle to the app's environment: resources, the theme, files, system services, and the ability to start components. The two you use most:
- Application Context (
applicationContext): the singleApplicationobject of the process. It lives as long as the process. Safe to keep in singletons and other objects that outlive a screen. - Activity Context (the
Activityitself, orrequireContext()in aFragment): carries the Activity's theme and window, and lives only until the Activity is destroyed. AFragmentis not aContext.
The class hierarchy: Activity extends ContextThemeWrapper, which extends ContextWrapper. Application and Service extend ContextWrapper directly. Each wrapper delegates to its own base ContextImpl that the system creates for it. Calling getApplicationContext() on any of them returns the process's Application object.
| Use case | Context to use | Why |
|---|---|---|
Singletons, repositories, SharedPreferences, databases | Application | Must outlive every Activity |
| Inflating views, reading theme attributes | Activity | Needs the Activity's theme |
Dialog, AlertDialog, PopupWindow | Activity | Needs a window token |
startActivity in the same task | Activity | A non-Activity Context needs FLAG_ACTIVITY_NEW_TASK |
Toast.makeText, getString without theming | Either | No window or theme needed |
The leak mechanism: a long-lived object (a singleton, a static field, a coroutine in GlobalScope) holds a strong reference to an Activity. The garbage collector cannot free the Activity while that reference chain is reachable. After rotation, the new Activity exists alongside the old one, which can never be collected.
In Compose, LocalContext.current is usually the Activity (or a wrapper around it). Using it inside a composable is fine. Passing it to something that outlives the screen, such as a singleton or a coroutine in GlobalScope, leaks the Activity exactly the same way.
Notes
applicationContextis the Kotlin property forgetApplicationContext(). In practice it returns theApplicationinstance of your process.- An
Activityis aContext. Passingthisfrom an Activity gives an Activity Context. Fragment.contextis nullable: it isnullbeforeonAttachand afteronDetach. UserequireContext()only while the Fragment is attached, and never store the result in a long-lived object.- A
ViewModelshould usually not need a Context at all. Inject a repository instead. If it really needs one, useAndroidViewModel(which holds theApplication) or Hilt's@ApplicationContext. - Hilt provides
@ApplicationContextand@ActivityContextqualifiers. Only@ApplicationContextcan be injected into singletons and ViewModels. - Starting an Activity from a non-Activity Context (a
Service, aBroadcastReceiver, the Application) withoutFLAG_ACTIVITY_NEW_TASKthrowsAndroidRuntimeException. - Since Android 10, apps in the background are largely blocked from starting activities at all. From a service or worker, show a notification with a
PendingIntentinstead. - A delayed
RunnableorMessageposted to aHandlerkeeps whatever it captures alive until it runs. If it captures the Activity, the Activity leaks for that long. Remove callbacks inonStoporonDestroy, or uselifecycleScope. - On a configuration change such as rotation, the old Activity is destroyed and a new one created. Any stored reference to the old Activity now points at a dead screen.
Code example
A repository that must live for the whole process receives the Application Context through Hilt. The ViewModel never sees a Context at all.
@Singleton
class UserRepository @Inject constructor(
@ApplicationContext private val appContext: Context, // never an Activity
) {
private val prefs: SharedPreferences =
appContext.getSharedPreferences("user", Context.MODE_PRIVATE)
fun saveLastUserId(id: String) {
prefs.edit { putString("last_user_id", id) } // core-ktx extension
}
fun loadLastUserId(): String? = prefs.getString("last_user_id", null)
}
// RIGHT: the ViewModel depends on the repository, not on a Context.
@HiltViewModel
class ProfileViewModel @Inject constructor(
private val repository: UserRepository,
) : ViewModel() {
fun onLogin(id: String) = repository.saveLastUserId(id)
}
// WRONG: the ViewModel survives rotation, so it keeps the old Activity alive.
class BadViewModel(private val activity: Activity) : ViewModel() {
fun openSettings() {
// After rotation this is the destroyed Activity.
activity.startActivity(Intent(activity, SettingsActivity::class.java))
}
}@ApplicationContextmakes the intent explicit, and Hilt refuses to inject an Activity into a@Singletonor aViewModelbecause those components have no Activity binding.SharedPreferencesdoes not need a window or theme, so an Activity Context adds risk with no benefit.BadViewModelis the exact pattern that produces a LeakCanary report: aViewModel(which survives configuration changes) holding anActivity. To open a screen, the ViewModel should emit an event and let the UI navigate.
Run the idea in plain Kotlin
A model of a long-lived service that keeps whatever Context it is given. The "leak" is a reference to a screen that is already destroyed.
abstract class Ctx(val id: Int) {
var destroyed = false
}
class AppCtx(id: Int) : Ctx(id)
class ActCtx(id: Int) : Ctx(id) {
fun destroy() {
destroyed = true
}
}
class LongLivedService {
private var ctx: Ctx? = null
fun start(c: Ctx) {
ctx = c
println("Service started, ctx id=" + c.id)
}
fun stop() {
ctx = null
println("Service stopped")
}
// Holding a destroyed Activity is a leak: it can never be collected.
fun isLeaking(): Boolean {
val c = ctx
return c is ActCtx && c.destroyed
}
}
fun main() {
val app = AppCtx(1)
val act = ActCtx(2)
// Bad path: the service holds an Activity Context
val svc = LongLivedService()
svc.start(act)
act.destroy()
println("After destroy, leaks? " + svc.isLeaking()) // true
svc.stop()
// Good path: the service holds the Application Context
val svc2 = LongLivedService()
svc2.start(app)
println("App ctx, leaks? " + svc2.isLeaking()) // false
svc2.stop()
}In production
- Crashlytics showed a rise in
OutOfMemoryErrorafter a release that added a global analytics singleton. - Each Fragment registered a listener with the singleton in
onViewCreatedand never removed it. The listener was an inner class, so it held the Fragment, and through it the Activity. - Each rotation added another listener, so every old Activity and its View tree stayed in memory.
- The crash appeared mostly on low-RAM devices in long sessions.
- Reproduced in a debug build with LeakCanary by rotating several times; the leak trace pointed to the singleton's listener list.
- Unregistered the listener in
onDestroyView, and changed the singleton to takeapplicationContextfor the work it actually needed. - Added LeakCanary's instrumentation artifact to UI tests so a test fails when it leaves a retained Activity behind.
- Users reported a crash when a background upload finished after they had navigated away from the upload screen.
- The upload coroutine ran in
GlobalScopeand captured the Activity. When it finished it calledAlertDialog.Builder(activity).show(). - The Activity was already finished, so showing the dialog threw
WindowManager$BadTokenException("is your activity running?").
- Moved the upload into the ViewModel with
viewModelScope, and exposed the result as state that the screen collects withrepeatOnLifecycle(orcollectAsStateWithLifecyclein Compose). - The screen decides whether to show the dialog, so it is only shown while the UI is visible.
- For uploads that must finish after the user leaves, moved the work to WorkManager and reported the result with a notification instead of a dialog.
Common mistakes
- Passing this (the Activity) into a ViewModel constructor. The ViewModel outlives the Activity across configuration changes and keeps the old Activity and its View tree in memory. Inject a repository, or the Application Context if you truly need one.
- Storing Fragment.context or requireContext() in a long-lived object. It is the Activity, so the object leaks the Activity. Pass the Context only into the call that needs it.
- Posting a delayed Runnable that captures the Activity. The message queue holds the Runnable, and the Runnable holds the Activity, until it runs. Remove callbacks when the screen stops, or use
lifecycleScopeso the work is cancelled. - Calling startActivity from a Service without FLAG_ACTIVITY_NEW_TASK. It throws
AndroidRuntimeException. And even with the flag, Android 10+ usually blocks activity starts from the background; show a notification instead. - Passing LocalContext.current to a singleton or a coroutine that outlives the screen. It is the Activity (or wraps it), so it leaks. Use
LocalContext.current.applicationContextfor anything that outlives the composition. - Using applicationContext for UI. It has no window token and only the application theme. A Dialog built from it crashes with
BadTokenException, and views inflated from it ignore the Activity's theme.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between the Application Context and an Activity Context?”
“When is it safe to pass an Activity Context to a ViewModel?”
“How does a Context leak cause an OutOfMemoryError?”
“What happens if you call startActivity from a Service without FLAG_ACTIVITY_NEW_TASK?”
Quiz
A repository singleton needs a Context to open SharedPreferences. Which Context should it keep?
What does getApplicationContext() return when called on an Activity?
What happens when you call AlertDialog.Builder(applicationContext).setMessage("Hi").show()?
Which change avoids leaking an Activity from a long-running coroutine?
0 of 4 answered
Mini task
15-minute exercise: find and fix a Context leak
- Open a project that has ViewModels or singletons (an
object, a Hilt@Singleton, or acompanion objectwith a storedContext). - Search for every place an
Activity,requireContext()orLocalContext.currentis passed into one of these long-lived objects. Also look for fields of typeContext,ActivityorViewin them. - For each hit, either remove the dependency, or change it to
@ApplicationContext context: Context(Hilt) orcontext.applicationContext. - If the object starts an Activity, move that into the UI: the long-lived object exposes state or an event, and the screen navigates.
- Add LeakCanary to the debug build (
debugImplementation), run the app, and rotate the screen several times on every screen you changed. - Done condition: LeakCanary reports no retained Activities after the rotations, and the app still works on every screen you touched.