In Android programming, what exactly is a Context
class and what is it used for?
I read about it on the developer site, but I am unable to understand it
The Context in Android is actually the context of what we are talking about and where we are currently present. This will become more clear as we go along with this.
Few important points about the context:
Context
is almost everywhere in Android Development and it is the most important thing in Android Development, so we must understand to use it correctly.
Wrong use of Context
can easily lead to memory leaks in an android application.
As there are different types of context in Android, we as an Android Developer often get confused about which context to use at which place. So let’s understand what are those, how to use those, and when to use which one.
Mainly two types of context:
Application Context
It is an instance that is the singleton and can be accessed in activity via getApplicationContext()
. This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of activity.
Example Use: If you have to create a singleton object for your application and that object needs a context, always pass the application context.
If you pass the activity context here, it will lead to the memory leak as it will keep the reference to the activity and activity will not be garbage collected.
In case, when you have to initialize a library in an activity, always pass the application context, not the activity context.
You only use getApplicationContext()
when you know you need a Context
for something that may live longer than any other likely Context
you have at your disposal.