What is Context in Android

While developing Android applications, we all see and use the term context. But for most new programmers its a nightmare to resolve a context related error. This post helps you understand what context really means in Android

Context in Android is an 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.

Every boss has an assistant to look after, to do all less important and time consuming tasks. If a file or a cup of coffee is needed, assistant is on the run. Some bosses barely know what’s going on in the office, so they ask their assistants regarding this too. They do some work themselves but for most other things they need help of their assistants.
In this scenario,
  • Boss –  is the Android application
  • Assistant – is context
  • Files/Cup of coffee  – are resources
Read the official documentation above once again and check if that makes sense now.
We generally call context when we need to get information about different parts of our application like Activities, Applications etc.
Some operations(things where assistant is needed) where context is involved:
  1. Loading common resources
  2. Creating dynamic views
  3. Displaying Toast messages
  4. Launching Activities etc.
Different ways of getting context:
  • getContext()
  • getBaseContext()
  • getApplicationContext()
  • this

  • EditText et = new EditText(getContext());
  • Toast toast = Toast.makeText(ActivityName.this, “Wow I am getting everything now. Cool..!! :)”, Toast.LENGTH_LONG).show();

Components which are accessed Implicitly: intents, broadcasts, content providers etc. 

Comments

Post a Comment

Popular posts from this blog

Difference Between View and ViewGroup

How to remove ActionBar from Android Activity