Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'Context' on Android?

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 clearly.

like image 661
Brigadier Avatar asked Aug 26 '10 06:08

Brigadier


People also ask

What is the difference between activity and context?

Anyways, it's not completely right to say that Activity is a Context, Activity is a more complex object, while Context is just a block that holds the information and gives the access to resources. "An Activity context lasts, as long as your app is alive, while the Activity context dies with your Activity" seems off.

What is an app context?

Application Context: It is the application and we are present in Application. For example - MyApplication(which extends Application class). It is an instance of MyApplication only. Activity Context: It is the activity and we are present in Activity. For example - MainActivity.

What is context menu android?

A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.

What is context parameter in Android?

Context is an abstract class whose implementation is given by Android system. It helps in using the application resources, launching activities, broadcast and many more. It tells the compiler to which context activity or application your current belongs which you want to show.


1 Answers

Putting it simply:

As the name suggests, it's the context of the 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, ...); 
like image 189
Sameer Segal Avatar answered Sep 28 '22 19:09

Sameer Segal