What is Context in Android?


Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc. More: http://developer.android.com/reference/android/content/Context.html

and simple answer on stackoverflow gives by Sameer Segal.
As the name suggests, its 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, package/application)
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).
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, ...);
Code Here Code explain on video , Watch on youtube:

Vogella gives example, you can check the size of the current device display via the Context.
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. More: http://www.vogella.com/tutorials/Android/article.html

Happy Coding!!!                                
What is Context in Android? What is Context in Android? Reviewed by D Kshetri on 10:36 AM Rating: 5

No comments:

Powered by Blogger.