Android Context 101 with Class Diagram
Beginner’s Guide to understand the fundamental of Context with class diagram in Android app development
You may find
Context in Android app development is confusing. For example, which one you should use?
Before answering that, let’s look at the
Context class diagram below to understand its relationship with other classes/components.
Context Class Diagram
From the class diagram above, you can tell
As you can see, there are
ContextThemeWrapper that extends
ContextWrapper that extends
Context. Here are the brief descriptions of all 3 classes.
Contextis an abstract class that allows an Android application to access system resources and interact with the operating system
ContextWrapperis a convenient way to modify the behavior of a Context object, such as adding additional functionality or overriding existing behavior, without changing the original Context itself.
ContextThemeWrapperallows you to change the visual appearance of an activity or view by applying a different theme to it
The most important thing to understand here is
ContextWrapper has a
mBase member variable which holds the
Context reference (called Base Context) from the Android system which creates it.
For example, when an
Activity is created by an Android system, a newly created
Context (from the Android system) is passed into the
ContextWrapper (held by the
mBase member variable).
So after an Activity is created, it consists of 3 context objects now:
- Application Context — Can be retrieved by calling
GetApplicationContext(). This is the same object instance throughout the whole application.
- Base Context — Can be retrieved by calling
GetBaseContext(). This is a newly created Context every time an activity is created.
- Activity Context — The activity…