Tuesday, April 13, 2010

Some notes about Android Context



Context is an interface to global information about an application environment. It's an abstract class whose implementation is provided by the Android system.

Context allows access to application-specific resources and classes, as well as calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

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 an Activity Context that the developer passes to classes and methods that need a Context.

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.

Here's a quick snippet showing how you can find both the Activity Context and the Application Context:


public class MyActivity extends Activity {
public void aMethod() {
Context actContext = this; /*returns the Activity Context since Activity extends Context.*/

Context appContext = getApplicationContext(); /*returns the context of the single, global Application object of the current process. */

Button btnGoToFirstAct = (Button) findViewById(R.id.btnGoToAct1);
Context vwContext = btnGoToFirstAct.getContext(); /*returns the context of the View. */



When run in the debugger, you can see the results of this:


 Notice that the vwContext in this case also returns the Activity Context.



Hope that helps answer some questions. Drop me a message in the comments if you have anything to add.

6 comments:

  1. Really nice and clear but i have a doubt that is
    does view.getContext()always return Activity Context?

    ReplyDelete
    Replies
    1. Hi "Where does India go?",
      .. Yes as far as I know it always returns an Activity Context.
      Do you know of a circumstance where view.getContext would return an Application Context?

      Cheers,
      Glenn

      Delete
  2. What might be the exception when you pass the application Context into the LayoutInflator

    ReplyDelete