Context: application vs activity

Learn the difference between Application and Activity Context in Android to prevent memory leaks and avoid crashes when using ViewModels or Dialogs. About 25 minutes.

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 single Application object 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 Activity itself, or requireContext() in a Fragment): carries the Activity's theme and window, and lives only until the Activity is destroyed. A Fragment is not a Context.

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 caseContext to useWhy
Singletons, repositories, SharedPreferences, databasesApplicationMust outlive every Activity
Inflating views, reading theme attributesActivityNeeds the Activity's theme
Dialog, AlertDialog, PopupWindowActivityNeeds a window token
startActivity in the same taskActivityA non-Activity Context needs FLAG_ACTIVITY_NEW_TASK
Toast.makeText, getString without themingEitherNo 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.

How one stored context leaks a screen
How one stored context leaks a screen After the user rotates the phone the old Activity is destroyed; if a singleton holds the Activity context, the Activity and its views stay in memory as a leak, but if it holds the applicationContext the garbage collector frees the old Activity. ACTIVITY CONTEXT applicationContext User rotates the phone configuration change Old Activity destroyed onDestroy() What does the singleton hold? Leak: Activity stays views and all, in memory Old Activity is freed garbage collected
Only the context you store decides it: an Activity context keeps the destroyed screen alive, applicationContext lets it go.

Notes

  • applicationContext is the Kotlin property for getApplicationContext(). In practice it returns the Application instance of your process.
  • An Activity is a Context. Passing this from an Activity gives an Activity Context.
  • Fragment.context is nullable: it is null before onAttach and after onDetach. Use requireContext() only while the Fragment is attached, and never store the result in a long-lived object.
  • A ViewModel should usually not need a Context at all. Inject a repository instead. If it really needs one, use AndroidViewModel (which holds the Application) or Hilt's @ApplicationContext.
  • Hilt provides @ApplicationContext and @ActivityContext qualifiers. Only @ApplicationContext can be injected into singletons and ViewModels.
  • Starting an Activity from a non-Activity Context (a Service, a BroadcastReceiver, the Application) without FLAG_ACTIVITY_NEW_TASK throws AndroidRuntimeException.
  • 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 PendingIntent instead.
  • A delayed Runnable or Message posted to a Handler keeps whatever it captures alive until it runs. If it captures the Activity, the Activity leaks for that long. Remove callbacks in onStop or onDestroy, or use lifecycleScope.
  • 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))
    }
}
  • @ApplicationContext makes the intent explicit, and Hilt refuses to inject an Activity into a @Singleton or a ViewModel because those components have no Activity binding.
  • SharedPreferences does not need a window or theme, so an Activity Context adds risk with no benefit.
  • BadViewModel is the exact pattern that produces a LeakCanary report: a ViewModel (which survives configuration changes) holding an Activity. 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

OOM crash after many rotations
  • Crashlytics showed a rise in OutOfMemoryError after a release that added a global analytics singleton.
  • Each Fragment registered a listener with the singleton in onViewCreated and 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.
The fix
  • 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 take applicationContext for the work it actually needed.
  • Added LeakCanary's instrumentation artifact to UI tests so a test fails when it leaves a retained Activity behind.
Crash when a dialog opens after the user left the screen
  • Users reported a crash when a background upload finished after they had navigated away from the upload screen.
  • The upload coroutine ran in GlobalScope and captured the Activity. When it finished it called AlertDialog.Builder(activity).show().
  • The Activity was already finished, so showing the dialog threw WindowManager$BadTokenException ("is your activity running?").
The fix
  • Moved the upload into the ViewModel with viewModelScope, and exposed the result as state that the screen collects with repeatOnLifecycle (or collectAsStateWithLifecycle in 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 lifecycleScope so 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.applicationContext for 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

  1. Open a project that has ViewModels or singletons (an object, a Hilt @Singleton, or a companion object with a stored Context).
  2. Search for every place an Activity, requireContext() or LocalContext.current is passed into one of these long-lived objects. Also look for fields of type Context, Activity or View in them.
  3. For each hit, either remove the dependency, or change it to @ApplicationContext context: Context (Hilt) or context.applicationContext.
  4. If the object starts an Activity, move that into the UI: the long-lived object exposes state or an event, and the screen navigates.
  5. Add LeakCanary to the debug build (debugImplementation), run the app, and rotate the screen several times on every screen you changed.
  6. Done condition: LeakCanary reports no retained Activities after the rotations, and the app still works on every screen you touched.
Next: Tasks and the back stack