What is the Context in Android Development?
Application Context vs Activity Context
What exactly is Context?
In general, context refers to what we are considering or the situation in which an event occurs.
In Android, a context simply refers to the current state of the application or object.
A few key points about the context:
It can be used to obtain information about the activity and the application.
It is the context of the application's current state.
The Activity and Application classes are both extensions of the Context class.
It can be used to gain access to resources, databases, shared preferences, and other similar things.
Context is almost everywhere in Android Development, and it is the most important thing to understand in order to use it correctly.
The incorrect use of Context can easily result in memory leaks in an Android application.
There are primarily two types of context:
1- Application Context
2- Activity Context
1- Application Context
It is a singleton instance that can be accessed in activity via getApplicationContext ().
This context is linked to an application's lifecycle.
2- Activity Context
An activity provides this context. This context is linked to an activity's lifecycle.
Activity Context has its own set of features:
Layout Inflation
Load Resource Values
Start an Activity
Show a Dialog
Bind to a Service
Start a Service
Register BroadcastReceiver
Send a Broadcast
Context can be accessed using one of three methods:
getContext(): returns the context of the linked activity.
Context(): returns the application's context, which contains all of the activities that are currently running.
getBaseContext(): This function is related to ContextWrapper, which wraps an existing context and allows us to modify its behavior.