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
In Java, we say this keyword refers to the state of the current object of the application.
Similarly, in an alternate we have Context
in Android Development.
This can be defined either explicitly or implicitly,
Context con = this;
getApplicationContext();
getBaseContext();
getContext();
Context is basically for resource access and getting the environment details of the application(for application context) or activity (for activity context) or any other...
In order to avoid memory leak you should use application context for every components that needs a context object.... for more click here
Context
means current.
Context
use to do operation for current screen.
ex.
1. getApplicationContext()
2. getContext()
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();
for more details about context, read this article. I will explain that briefly.
If you wanna know what is context you must know what it does...
for example getContext() is one of the methods that retrieve context. In getContext(), Context is tied to an Activity and its lifecycle. We can imagine Context as layer which stands behind Activity and it will live as long as Activity lives. The moment the Activity dies, Context will too. this method gives list of functionalities to activity, like:
Load Resource Values,
Layout Inflation,
Start an Activity,
Show a Dialog,
Start a Service,
Bind to a Service,
Send a Broadcast,
Register BroadcastReceiver.
now imagine that :
Context is a layer(interface) which stands behind its component (Activity, Application…) and component’s lifecycle, which provides access to various functionalities which are supported by application environment and Android framework.
Instances of the the class android.content.Context provide the connection to the Android system which executes the application. For example, you can check the size of the current device display via the Context.
It also gives access to the resources of the project. It is the interface to global information about the application environment.
The Context class also provides access to Android services, e.g., the alarm manager to trigger time based events.
Activities and services extend the Context class. Therefore they can be directly used to access the Context.
Think of Context as a box with different resources: string, colors, and fonts. If you need a resource, you turn to this box. When you rotate the screen, this box changes because the orientation changes to landscape.