Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 104 ยท Getting Started

Context in Android

Understand Android's Context: Application vs Activity vs Service context, which one to use, how leaks happen, LocalContext in Compose, ContextWrapper and themed contexts.

Almost every Android API you touch asks for a Context: starting an activity, reading a string resource, opening a database, showing a toast, getting a system service. Beginners pass this until the compiler is happy, and then hit one of three surprises: a crash that mentions a missing window token, a theme that does not apply, or an app that slowly eats memory. All three come from the same misunderstanding of what a Context is.

A Context is a handle to the environment your code runs in. It lets you reach resources, files, system services, the current theme and the ability to start other components. Different contexts carry different parts of that environment, and, importantly, different lifetimes. This lesson explains the context types, which one to choose, how a wrong choice causes memory leaks, how Compose gives you the context, and how ContextWrapper and themed contexts work. The Android classes cannot run here, so the real code is read-only; the TryIts are plain Kotlin stand-ins that model the class hierarchy and the leak.

What a Context is

Context is an abstract class. You never create one yourself; the system gives you instances that live on a small family tree.

flowchart TD
    C["Context (abstract)"] --> CI["ContextImpl<br/>(the real work)"]
    C --> CW["ContextWrapper<br/>(delegates to another Context)"]
    CW --> App["Application"]
    CW --> Svc["Service"]
    CW --> CTW["ContextThemeWrapper<br/>(adds a theme)"]
    CTW --> Act["Activity"]

Application, Service and Activity are all wrappers around a base context. An Activity adds a theme and a window.

The actual implementation is a hidden ContextImpl. Application, Service and Activity extend ContextWrapper, a class that holds another context (its base context) and forwards every call to it. That is the decorator pattern: the wrapper changes a few things and delegates the rest. An Activity is a ContextThemeWrapper, which adds a theme.

What you can do with a context:

  • load resources: getString(R.string.title), getColor(...), resources.displayMetrics
  • reach app files and databases: filesDir, cacheDir, openFileInput, Room's Room.databaseBuilder(context, ...)
  • get system services: getSystemService(...)
  • send and register broadcasts, start services, see Broadcast Receivers
  • start activities, see Intents
  • check permissions, see Runtime Permissions

Application vs Activity vs Service context

The three you meet daily differ in lifetime and in what they can do.

Application context Activity context Service context
Lives As long as the process As long as that Activity instance As long as that Service
Has the activity theme No (app theme only) Yes No (app theme)
Can show a dialog or add a window No (crash) Yes No
Can startActivity Only with FLAG_ACTIVITY_NEW_TASK Yes Only with FLAG_ACTIVITY_NEW_TASK
Safe to store in a long-lived object Yes No (leak) No

Reading across the table:

  • Application context (applicationContext) is a singleton for the process. It is the right choice for anything that outlives a screen: a database, an image loader, a repository, an analytics client. It cannot show UI.
  • Activity context is the one you need for anything the user sees: dialogs, toasts with custom views, LayoutInflater for themed views, starting an activity without an extra flag. It dies when the activity is destroyed, which includes every rotation.
  • Service context behaves like the application context but is tied to the service's lifetime.

A very common crash is showing an AlertDialog built with the application context:

Kotlin
// read-only example: what goes wrong
val dialog = AlertDialog.Builder(applicationContext)   // crashes when shown
    .setMessage("Delete this note?")
    .create()
dialog.show()
// android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid

A dialog needs a window, windows belong to activities, and only the activity context knows its window token. Similarly, startActivity from a non-activity context throws AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag unless you add that flag yourself (which puts the new screen in a new task, rarely what you want in the middle of your own UI).

The first stand-in models the family tree and these three rules with plain Kotlin: a base context, wrappers, and the checks the platform performs.

Kotlin Context hierarchy and what each one can do (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The third scenario explains a classic styling bug: views inflated with the application context ignore the theme overlay you set on one activity, so a "dark" screen suddenly has a light dialog. Pass the context of the screen that owns the UI.

Memory leaks from the wrong context

An activity is a large object: it holds its views, their bitmaps, and the whole view tree. The system destroys it on rotation and when the user leaves, expecting the garbage collector to free it. If some long-lived object still references the destroyed activity, the collector cannot free it, and you have a memory leak. Do that on every rotation and memory grows until the app is killed.

The classic version looks innocent:

Kotlin
// read-only example: a leak
object ImageCache {
    lateinit var context: Context      // a global that outlives every screen

    fun init(context: Context) {
        this.context = context         // MainActivity passes "this"
    }
}

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ImageCache.init(this)          // BUG: the object now keeps the first activity alive forever
    }
}

The fix is to store only the application context, which lives as long as the process anyway:

Kotlin
// read-only example: the fix
fun init(context: Context) {
    this.context = context.applicationContext
}

Other common leak sources are an inner class or lambda that captures the activity and lives longer (a Handler with a delayed message, a callback registered with a long-lived listener and never removed, a coroutine in GlobalScope), static references to views, and singletons that take a Context parameter and keep it. The rule of thumb is: do not store an Activity context in anything that outlives the Activity. Use viewModelScope and lifecycle-aware components so work is cancelled with the screen. A ViewModel must never hold a reference to an Activity or a View either; if it needs a context for resources, extend AndroidViewModel or inject the application context.

The second stand-in is a tiny heap. It marks everything reachable from the roots (the "GC roots", here a static singleton) and shows which activity objects the collector may free. A singleton event bus keeps a list of listeners; the leaky version registers each new activity and never removes it.

Kotlin How a singleton leaks an Activity (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the leaky run every new screen adds another activity that can never be freed, along with its entire view tree. In the fixed run the old activity is unregistered, becomes unreachable and is collected. Tools like LeakCanary (a debug-only library) detect this on a real device and print the reference chain from the GC root to the leaked activity.

Getting a context in Compose

In Compose you read the current context with LocalContext:

Kotlin
// read-only example
@Composable
fun ShareButton(text: String) {
    val context = LocalContext.current          // usually the host Activity
    Button(onClick = {
        val send = Intent(Intent.ACTION_SEND).apply {
            type = "text/plain"
            putExtra(Intent.EXTRA_TEXT, text)
        }
        context.startActivity(Intent.createChooser(send, null))
    }) { Text("Share") }
}

LocalContext.current is whatever the host passed to setContent, normally your activity, but it can be a ContextWrapper around it (for example inside a dialog or when a library wraps it). When you really need the Activity, unwrap it instead of casting:

Kotlin
// read-only example
fun Context.findActivity(): Activity? {
    var current: Context = this
    while (current is ContextWrapper) {
        if (current is Activity) return current
        current = current.baseContext
    }
    return null
}

Do not capture LocalContext.current in a long-lived object such as a ViewModel. Pass the data or a function, or inject the application context with @ApplicationContext (see Hilt). Keep composables previewable by taking lambdas (onShare: () -> Unit) and calling the context only in the screen-level composable.

Which context for what

You want to... Use
Show a dialog, a snackbar anchored in the UI, or a themed view Activity (or LocalContext.current in Compose)
Start an activity in the normal flow Activity
Build a database, an image loader, a DataStore applicationContext
Read a string or dimension Any (but prefer the one nearest the UI, for the right locale and configuration)
Register a broadcast receiver for the whole app applicationContext (and unregister when done)
Start a service or schedule work Application is fine
Work inside a ViewModel AndroidViewModel / injected application context

One more detail: the configuration. An Activity context reflects the current configuration, including night mode, locale override and window size. The application context may be updated too, but derived contexts (createConfigurationContext) are the proper tool for forcing a different locale or density, and they return a new context that does not change the original.

getContext, getBaseContext and getApplicationContext

Different Context accessors return different things, and mixing them up is a classic source of leaks and crashes:

Call Where Returns
this inside an Activity or Service that component, which is a Context
getContext() / requireContext() inside a Fragment or View the Activity (or the themed context the view was inflated with)
getApplicationContext() anywhere you have a Context the single Application object, alive as long as the process
getBaseContext() inside a ContextWrapper (every Activity and Service is one) the context that the wrapper decorates, usually the implementation behind the Activity
setBaseContext() internal, called by the system once you almost never call it

Use this or the Activity context for anything visual: dialogs, themed inflation, starting an Activity with the right task. Use applicationContext for long-lived objects such as a database, a repository, an analytics client or a singleton, so they cannot keep a destroyed Activity alive (see "Memory leaks from the wrong context" above). getBaseContext() is rarely what you want: it skips the wrapper's overrides, for example a locale or theme wrapper. Reach for it only when a library explicitly asks you to unwrap a ContextWrapper, as in the helper in the Compose section above.

ContextWrapper and themed contexts

Because ContextWrapper delegates to a base context, you can subclass it to change behavior without touching the original. Libraries do this to attach a different locale, theme or file directory.

Kotlin
// read-only example: a themed wrapper
val darkContext = ContextThemeWrapper(context, R.style.Theme_MyApp_Dark)
val inflater = LayoutInflater.from(darkContext)
val view = inflater.inflate(R.layout.card, parent, false)    // inflated with the dark theme

The wrapper keeps the same base context (so same resources, same files) and answers theme questions with the new style. In Compose you rarely need this because themes are composable (MaterialTheme { ... } around a subtree, see Material 3 Theming). ContextWrapper and themed contexts mostly matter for the View system, for dialogs with a custom style and for interop.

Android also separates contexts that are visual (tied to a display and a window: activities, and contexts made with createWindowContext or createDisplayContext) from those that are not (application, services). From Android 11, StrictMode can flag a "incorrect context use" when you use a non-visual context to get a WindowManager or inflate UI. Treat the warning as a signal to pass the activity context instead.

Common mistakes

  • Showing a dialog or starting an activity from the application context. It either crashes or opens in a new task.
  • Storing this (an Activity) in a singleton, companion object or static field. That is the classic leak.
  • Inflating views with the application context and wondering why night mode or the activity theme is ignored.
  • Casting LocalContext.current as Activity. It throws when the context is wrapped; unwrap with ContextWrapper.
  • Holding a Context in a ViewModel. Use AndroidViewModel or inject the application context.
  • Using GlobalScope or long-lived callbacks that capture an activity. Tie work to lifecycleScope or viewModelScope.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which context can safely be stored in a singleton that lives as long as the process?

    The application context lives as long as the process, so holding it cannot keep a destroyed screen alive. Holding an Activity can.
  2. 2. Why does an AlertDialog built with applicationContext crash when shown?

    Showing a window requires a token from an activity. The application context has none, so the system throws a BadTokenException.
  3. 3. How do Application, Service and Activity relate to ContextWrapper?

    They are decorators around a hidden ContextImpl. A wrapper can change some behavior (such as the theme) and forward the rest.
  4. 4. In Compose, what is the safest way to get the Activity from LocalContext.current?

    The current context may be a ContextWrapper around the activity. Walking the baseContext chain finds it without a ClassCastException.

Summary

  • A Context is a handle to the app environment: resources, files, system services, themes and the ability to start components.
  • Application, Service and Activity are ContextWrappers; Activity adds a theme and a window.
  • Use the application context for long-lived objects and the activity context for UI such as dialogs and themed views.
  • Storing an Activity in anything that outlives it, including singletons, listeners and global scopes, leaks the whole view tree.
  • In Compose, read the context with LocalContext.current, unwrap it to find the activity and never cache it in a ViewModel.
  • ContextWrapper and ContextThemeWrapper let you change theme, locale or behavior without touching the original.
  • The Android code is read-only; the TryIts model the context hierarchy and a leak with plain Kotlin.

Next: The Four Components and How Android Runs Your App