Context Usage Pitfalls on Android
Context Usage Pitfalls on Android
Context is one of the most frequently used objects in Android development. It provides access to application resources, system services, databases, shared preferences, and the file system. However, improper usage of Context is also one of the most common sources of memory leaks, crashes, and subtle bugs. Understanding which Context to use in which situation and how to avoid retaining it beyond its lifecycle is a recurring interview topic. By the end of this lesson, you will be able to:
- Distinguish between
Activitycontext andApplicationcontext and their appropriate use cases. - Identify how retaining an
Activitycontext in a long lived object causes memory leaks. - Explain why
Applicationcontext is inappropriate for UI operations like showing dialogs. - Describe the threading constraints when using
Contextfor UI operations.
Activity Context vs Application Context
Android has two main types of Context that developers work with directly. Activity context is tied to the lifecycle of a specific Activity instance. It carries the Activity's theme, window, and UI configuration. Application context lives for the entire duration of the application process and is not tied to any specific UI component.
The general rule is to use Activity context for UI operations and Application context for operations that outlive any single Activity:
// UI operation: use Activity context
val dialog = AlertDialog.Builder(activityContext)
.setTitle("Confirm")
.setMessage("Are you sure?")
.create()
// Non-UI operation: use Application context
val prefs = applicationContext
.getSharedPreferences("settings", Context.MODE_PRIVATE)
Using Application context to inflate layouts or create dialogs can cause issues because the Application context does not carry theme information. The resulting UI components will use the default system theme instead of the Activity's theme, leading to visual inconsistencies.
Memory Leaks from Context Retention
The most common Context related bug is retaining an Activity context in a long lived object. When an object holds a reference to an Activity and outlives it, the garbage collector cannot reclaim the Activity or any of the views and resources it holds:
// This causes a memory leak
object AppSingleton {
var context: Context? = null
}
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppSingleton.context = this // Leaks the Activity
}
}
This interview continues for subscribers
Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.
Become a Sponsor