Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is 'Context' on Android?

In Android programming, what exactly is a Context class and what is it used for?
by

3 Answers

RoliMishra
As the name suggests, it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in a class that extends from Context, such as the Application, Activity, Service and IntentService classes).

Typical uses of context:

Creating new objects: Creating new views, adapters, listeners:

TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);

Accessing standard common resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:

context.getSystemService(LAYOUT_INFLATER_SERVICE)
getApplicationContext().getSharedPreferences(name*, *mode);

Accessing components implicitly: Regarding content providers, broadcasts, intent

getApplicationContext().getContentResolver().query(uri, ...);
Sonali7
Context represents environment data that provides access to things such as databases. It provides services like resolving resources, obtaining access to preferences, and so on. Generally, things like Loading a resource, Launching a new activity, Creating views, and obtaining system service, involve context.
Shahlar1vxp
The context class in Android is known as an interface to global information about a certain application environment.
It is declared as an abstract class where implementation is offered by the Android Operating System. Context allows access to the application-specific resources and classes and up-calls for the application-level operations like launching activities, receiving intents, broadcasting, etc. Here is an example in which the abstract method getAssets is implemented from the Context class as follows-
@Override
public AssetManager getAssets() {
return mBase.getAssets();
}

where 'mBase' is a fieldset by the constructor to a certain context.
There are several ways of getting context-
getContext()
getBaseContext()
getApplicationContext()
this

Login / Signup to Answer the Question.