Context
Context
is the interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.1
In the following picture, you can see a hierarchy of classes, where Context
is the root class of this hierarchy. In particular, it’s worth emphasizing that Activity
is a descendant of Context
:2
The primary classes that implement Context
(through inheritance) are:
Application
. It provides access to application-wide resources and services and is used for global settings or shared data;Activity
. It is typically used for UI-related tasks, such as starting new activities (startActivity()
), accessing resources, and managing events;Service
. A context tied to the lifecycle of a service;ContextWrapper
. A base class for other context implementations that wrap an existingContext
. It allows extending and customizing the behavior of an existing context;ContextThemeWrapper
. Inherits fromContextWrapper
. It provides a context with a specific theme, often used in activities to apply UI themes withsetTheme()
.
What Context
can do?
The following table shows what actions can be performed with different types of Context.
- An application CAN start an
Activity
from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice; - This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application;
- Allowed if the receiver is
null
, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.
Difference between getApplication()
and getApplicationContext()
@Override
public Context getApplicationContext() {
return (mPackageInfo != null) ?
mPackageInfo.getApplication() : mMainThread.getApplication();
}
Actually both functions return application object since application itself is a context. So why android provide two functions? The reason is because getApplication()
is only able to be used in Activity
and Service
. In other components like BroadcastReceiver
is only able to use getApplicationContext()
to get application object.
Links
Fully understand Context
in Android
Difference between Activity Context and Application Context
Context and memory leaks in Android
Further reading
Which Context
should I use in Android?
Android Context
Needs Isolation
Using Context Theme Wrapper on Android
Activity Context vs Application Context: A Deep Dive into Android Development