Interview QuestionPractical QuestionFollow-up Questions

Context in Android

skydovesJaewoong Eum (skydoves)||7 min read

Context in Android

Context is the base class that provides access to application resources, system services, and component lifecycle information in Android. Every Activity, Service, Application, and BroadcastReceiver either is a Context or receives one. Choosing the wrong type of Context is one of the most common sources of memory leaks and crashes in Android development. By the end of this lesson, you will be able to:

  • Explain the role of Context and how it connects components to the Android system.
  • Distinguish between Application, Activity, Service, and BroadcastReceiver contexts.
  • Identify which context type to use for different operations.
  • Avoid memory leaks caused by retaining the wrong context reference.

What Context Provides

Context is an abstract class that gives components access to the Android environment. Through a Context, code can retrieve resources (getString(), getDrawable()), access system services (getSystemService()), start components (startActivity(), startService()), open databases, read shared preferences, and inflate layouts. Nearly every interaction with the Android framework requires a Context:

// Accessing resources
val appName = context.getString(R.string.app_name)

// Starting an activity
context.startActivity(Intent(context, DetailActivity::class.java))

// Getting a system service
val connectivityManager = context.getSystemService(
    Context.CONNECTIVITY_SERVICE
) as ConnectivityManager

Internally, Context delegates most operations to ContextImpl, which is the actual implementation created by the system. Activity and Service extend ContextWrapper, which wraps a ContextImpl instance and delegates calls to it.

Types of Context

Each component type provides a context with different characteristics and lifecycle behavior:

Application Context lives for the entire process lifetime. It is obtained via context.applicationContext or Application.getApplicationContext(). It does not hold references to any Activity view hierarchy, making it safe to store in singletons or long lived objects. However, it cannot be used for operations that require a UI context, such as showing dialogs or inflating views with the correct theme.

Activity Context is tied to the Activity lifecycle. It provides the current theme, window, and view hierarchy. It is required for UI operations like showing dialogs, inflating themed layouts, and starting activities with transitions. It is destroyed when the Activity is destroyed:

This interview continues for subscribers

Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.

Become a Sponsor