Friday, 30 March 2012

All about Context

Context

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

Context is used for many operations but mostly to load and access resources. This is why all the widgets receive a Context parameter in their constructor. In a regular Android application, you usually have two kinds of Context, Activity and Application. It’s usually the first one that the developer passes to classes and methods that need a Context.

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An android app has activities. It's like a handle to the environment your application is currently running in. The activity object inherits the Context object. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the app is running.

Basically the Application context is associated with the Application and will always be the same throughout the life cycle of your app, where as the Activity context is associated with the activity and could possible be destroyed many times as the activity is destroyed during screen orientation changes and such.

In particular you should be careful when dealing with anything that deals with the GUI that requires a Context. For example, 
if you pass the application Context into the LayoutInflator you will get an Exception. It's good practice to use an Activity's Context within that Activity, and the Application Context when passing a context beyond the scope of an Activity to avoid memory leaks. Click here to know more about Avoiding Memory Leaks in android.

You can get the context by invoking getApplicationContext(), getBaseContext() or this (when in the activity class).

this --- It will return the Activity context as Activity extends Context
getApplicationContext() --- Return the context of the single, global Application object of the current process. 
getBaseContext() --- Returns the base context as set by the constructor.

No comments:

Post a Comment