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.
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.
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.
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.
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.
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, ...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With