Which `Context` Should You Use in Android?

Which `Context` Should You Use in Android?

Which Context Should You Use in Android?

Context is everywhere in Android, but choosing the wrong one can lead to memory leaks, broken UI, or hard‑to‑debug crashes. This article explains what Context is, where it comes from, and how to pick the right type in real projects.

What is Context?

Context is an abstract class that provides global information about your app environment. It lets you access resources, start components, and interact with system services.

Important facts:

  • Context is abstract.
  • It provides global app information and access to system APIs.
  • Activity, Application, and Service all extend Context.

That means you’re almost always working with a specific kind of Context, not the abstract class itself.

What can you do with a Context?

Context allows you to:

  • Start an activity or service
  • Access resources (strings, drawables, dimensions)
  • Access system services (e.g., LayoutInflater, NotificationManager)
  • Open or manage databases
  • Read/write shared preferences

But the scope and lifecycle of the context matters for each of these tasks.

The three common context types

Activity context

  • Tied to a single screen
  • Destroyed when the activity is destroyed
  • Best for UI and theme‑dependent operations

Use it when you:

  • Inflate themed views
  • Show dialogs
  • Need screen‑level resources

Application context

  • Tied to the app process
  • Lives as long as the app is alive
  • Safe for long‑lived components

Use it when you:

  • Need a context in a singleton
  • Work in repositories, managers, or background tasks
  • Don’t need UI or theme styling

Service context

  • Tied to a background service lifecycle
  • Suitable for background operations

Quick rule of thumb

  • UI work → Activity context
  • Long‑lived work → Application context

Examples

UI dialog: use Activity context

AlertDialog.Builder(this)
    .setTitle("Delete")
    .setMessage("This can’t be undone.")
    .setPositiveButton("OK", null)
    .show()

Repository: use Application context

class UserRepository(appContext: Context) {
    private val prefs = appContext.getSharedPreferences("user", Context.MODE_PRIVATE)
}

Common mistakes

  • Holding Activity context in a singleton → memory leak
  • Using Application context for UI components that require theming
  • Passing Context blindly without understanding the component’s lifecycle

A simple checklist

Before passing a Context, ask:

  1. Will this object outlive an activity?
  2. Do I need UI or theme‑aware resources?
  3. Is this operation tied to a specific screen?

If 1 is yes, prefer Application context. If 2 or 3 is yes, use Activity context.

Wrap‑up

Context is your gateway to Android system services and app resources, but not all contexts are equal. Choose Activity context for UI and Application context for long‑lived work, and you’ll avoid most context‑related issues.